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

后端 未结 20 2335
孤独总比滥情好
孤独总比滥情好 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:53

    With x86 you can use SSE to test 16 bytes at a time:

    #include "smmintrin.h" // note: requires SSE 4.1
    
    int is_empty(const char *buf, const size_t size) 
    {
        size_t i;
        for (i = 0; i + 16 <= size; i += 16)
        {
            __m128i v = _mm_loadu_si128((m128i *)&buf[i]);
            if (!_mm_testz_si128(v, v))
                return 0;
        }
        for ( ; i < size; ++i)
        {
            if (buf[i] != 0)
                return 0;
        }
        return 1;
    }
    

    This can probably be further improved with loop unrolling.

    On modern x86 CPUs with AVX you can even use 256 bit SIMD and test 32 bytes at a time.

提交回复
热议问题