opencl中的bitcount实现

时间:2013-11-09 12:37:44

标签: opencl bit

我对内核的opencl实现感兴趣,它计算unsigned int中的set(1)位 我知道opencl有这样的扩展,我不想使用它,但我自己实现

2 个答案:

答案 0 :(得分:2)

这不是您正在寻找的确切功能。但由于没有人发布OpenCL代码,我会添加它。它是256位整数的OpenCL位计数代码,而不是您请求的32位。代码来自here。它使用Dithermaster指出的一种众所周知的算法。转换为32位应该不难。

//
// popcnt256 - return population count for 256-bit value
//
uint popcnt256 (ulong4 vreg)
    {
    const ulong4 m1  = (ulong4)(0x5555555555555555,0x5555555555555555,0x5555555555555555,0x5555555555555555);
    const ulong4 m2  = (ulong4)(0x3333333333333333,0x3333333333333333,0x3333333333333333,0x3333333333333333);
    const ulong4 m4  = (ulong4)(0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f);
    const ulong4 h01 = (ulong4)(0x0101010101010101,0x0101010101010101,0x0101010101010101,0x0101010101010101);

    vreg -= (vreg >> 1) & m1;
    vreg = (vreg & m2) + ((vreg >> 2) & m2);
    vreg = (vreg + (vreg >> 4)) & m4;
    vreg = (vreg * h01) >> 56;
    return vreg.s0 + vreg.s1 + vreg.s2 + vreg.s3;
    }

答案 1 :(得分:0)

大多数老式的基于CPU的技巧也适用于此,尽管任何循环在GPU上都不会很好。可能(非全局内存)表可能效果最好。

请参阅:

How to count the number of set bits in a 32-bit integer?

http://www.geeksforgeeks.org/count-set-bits-in-an-integer/

http://gurmeet.net/puzzles/fast-bit-counting-routines/