std::bitset<N>::count 与 __builtin_popcount

问题描述 投票:0回答:3

比较以下两个表达式

std::bitset<8>(5).count()
__builtin_popcount(5)

哪个更好?

c++ bit-manipulation bitset std-bitset hammingweight
3个回答
7
投票

根据 godbolt,bitsetpopcount 在最新的 g++ 上产生相同的 asm 输出。但是,正如评论中提到的,

__builtin_popcount
是 gcc 扩展,在 x86 之外的其他编译器和其他架构上均不可用。因此,bitset 选项显然更好。


6
投票
int  __builtin_popcount(unsigned int);

是 GCC 的内置函数,而

std::bitset<N>::count
是 C++ 标准。

两个函数执行相同的操作:返回设置为

true
的位数。

你应该使用什么?

总是倾向于使用C++标准的函数,因为其他编译器不支持

__builtin_popcount
函数。

更新

如果你看一下 Google Benchmark 工具所做的统计数据:

#include <bitset>

static void GccBuiltInPopCount(benchmark::State& state) {
    for (auto _ : state) {
        __builtin_popcount(5);
    }
}

BENCHMARK(GccBuiltInPopCount);

static void StdBitsetCount(benchmark::State& state) {
    for (auto _ : state) {
        std::bitset<8>(5).count();
    }
}

BENCHMARK(StdBitsetCount);

使用 GCC 9.2 和标志

-std=c++2a -O3
,GCC 内置函数比
std::bitset<N>::count()
函数慢 10%,但是,由于两个函数的 ASM 输出相同,基准测试的差异可能是由于其他因素造成的。


-1
投票

当你不知道

std::bitset<N>::count
中N的值时,我认为第二个更好

更新: 你可以尝试 std::popcount

© www.soinside.com 2019 - 2024. All rights reserved.