【问题标题】:What is the most efficient way of counting the number of 1's in an integer? [duplicate]计算整数中 1 的数量最有效的方法是什么? [复制]
【发布时间】:2012-02-11 21:17:17
【问题描述】:

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

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

我们想这样做 N~10^10 次。

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

【问题讨论】:

    标签: algorithm optimization numbers compiler-optimization


    【解决方案1】:

    实际上有几个选项,我认为本地方式太慢了。

    您可以使用查找表查找 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;
    

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2011-03-10
      • 2011-07-13
      • 1970-01-01
      • 2017-12-06
      • 2012-08-14
      • 1970-01-01
      • 2012-01-02
      • 2013-01-23
      相关资源
      最近更新 更多