std :: bitset< N> :: count与__builtin_popcount [英] std::bitset<N>::count vs __builtin_popcount
问题描述
比较以下两个表达式
std::bitset<8>(5).count()
__builtin_popcount(5)
哪个更好?
推荐答案
int __builtin_popcount(unsigned int);
是GCC的内置功能,而 std :: bitset< N> :: count
是C ++标准.
is a built in function of GCC while std::bitset<N>::count
is a C++ standard.
两个函数都做同样的事情:返回设置为 true
的位数.
Both function do the same thing: return the number of bits that are set to true
.
您应该使用什么?
总是倾向于使用C ++标准的函数,因为其他编译器不支持 __ builtin_popcount
函数.
Always tend to use C++ standard's functions because other compilers don't support __builtin_popcount
function.
更新
如果您查看由Google Benchmark工具提供的统计信息:
If you take a look at the statistics made by Google Benchmark tool:
#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输出相同,因此基准测试的差异可能是由于其他因素造成的.
with GCC 9.2 and flags -std=c++2a -O3
, GCC built in function is 10% slower than the std::bitset<N>::count()
function but, since the ASM output is the same for both function, the difference in benchmark could be due to other factors.
这篇关于std :: bitset< N> :: count与__builtin_popcount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!