Faster approach to checking for an all-zero buffer in C?

后端 未结 20 2389
孤独总比滥情好
孤独总比滥情好 2020-12-03 05:33

I am searching for a faster method of accomplishing this:

int is_empty(char * buf, int size) 
{
    int i;
    for(i = 0; i < size; i++) {
        if(buf[         


        
20条回答
  •  清歌不尽
    2020-12-03 05:48

    The benchmarks given above (https://stackoverflow.com/a/1494499/2154139) are not accurate. They imply that func3 is much faster than the other options.

    However, if you change the order of the tests, so that func3 comes before func2, you'd see func2 is much faster.

    Careful when running combination benchmarks within a single execution... the side effects are large, especially when reusing the same variables. Better to run the tests isolated!

    For example, changing it to:

    int main(){
      MEASURE( func3 );
      MEASURE( func3 );
      MEASURE( func3 );
      MEASURE( func3 );
      MEASURE( func3 );
    }
    

    gives me:

    func3: zero          14243
    func3: zero           1142
    func3: zero            885
    func3: zero            848
    func3: zero            870
    

    This was really bugging me as I couldn't see how func3 could perform so much faster than func2.

    (apologize for the answer, and not as a comment, didn't have reputation)

提交回复
热议问题