计算整数1的最有效方法是什么?

时间:2012-02-11 21:17:17

标签: algorithm optimization numbers compiler-optimization

  

可能重复:
  Best algorithm to count the number of set bits in a 32-bit integer?

给定32位无符号整数,我们希望计算其二进制表示中的非零位数。最快的方法是什么?

我们想做N~10 ^ 10次。

注意:由于当前cpu的架构,使用大型查找表通常不是一个好主意。在本地计算它比使用需要查看外部存储器的巨大阵列要快得多

1 个答案:

答案 0 :(得分:2)

实际上有几种选择,我认为本机方式对此来说太慢了。

您可以使用查找表获取8位值,并对来自unsigned int值的所有四个字节并行执行,然后对结果求和。这个也可以很好地兼容(无论是多核,还是某些SSE3 / 4都可以提供帮助)。

你也可以选择Brian Kernighan的解决方案:

unsigned int v;              // count the number of bits set in v
unsigned int c;              // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1;                // clear the least significant bit set
}

我前段时间找到的最后一种可能方式是(在64位计算机上,因为模运算在那里会非常快):

unsigned int v;      // count the number of bits set in v
unsigned int c;      // c accumulates the total bits set in v

c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;