Comparing the following two expressions
std::bitset<8>(5).count()
__builtin_popcount(5)
which one is better?
Comparing the following two expressions
std::bitset<8>(5).count()
__builtin_popcount(5)
which one is better?
On
When you don’t know the value of N in std::bitset<N>::count, I think the second one is better
update: you can try std::popcount
is a built in function of GCC while
std::bitset<N>::countis a C++ standard.Both function do the same thing: return the number of bits that are set to
true.What should you use?
Always tend to use C++ standard's functions because other compilers don't support
__builtin_popcountfunction.UPDATE
If you take a look at the statistics made by Google Benchmark tool:
with GCC 9.2 and flags
-std=c++2a -O3, GCC built in function is 10% slower than thestd::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.