更快的方法来检查在C全零缓冲区? [英] Faster approach to checking for an all-zero buffer in C?
问题描述
我在寻找实现这一点的一个更快的方法:
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[i] != 0) return 0;
}
return 1;
}
我意识到我在寻找一个微型的优化,除了在极端情况下是不必要的,但我知道一个更快的方法存在,并且我很好奇它是什么。
I realize I'm searching for a micro optimization unnecessary except in extreme cases, but I know a faster method exists, and I'm curious what it is.
推荐答案
在许多体系,比较1个字节所花的时间相同数量的4或8,有时甚至是16的4个字节通常容易(int或长)和8太(long或long long)。 16或更高版本可能需要内嵌汇编例如,使用矢量单元。
On many architectures, comparing 1 byte takes the same amount of time as 4 or 8, or sometimes even 16. 4 bytes is normally easy (either int or long), and 8 is too (long or long long). 16 or higher probably requires inline assembly to e.g., use a vector unit.
另外,一个分支误predictions痛啊,它可能有助于消除分支机构。例如,如果缓冲器几乎总是空的,而不是针对0测试每个块,位或它们一起并测试的最终结果。
Also, a branch mis-predictions really hurt, it may help to eliminate branches. For example, if the buffer is almost always empty, instead of testing each block against 0, bit-or them together and test the final result.
这篇关于更快的方法来检查在C全零缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!