I just knew that there are many builtin functions of gcc, some of them seems to be useful.
For example, the builtin function __builtin_popcount()
can count the number of one’s(set bits) in an integer.
Well, I know that different compiler may have different builtin function so using __builtin_popcount()
may cause some portability issue. But if we ignore this issue, what is the difference between builtin function and common c/c++ code? You see we can easily make a piece of code to count the number of one's(set bits) in integer too.
int main(void)
{
int i = 5;
std::cout << __builtin_popcount(i) << std::endl;
int j = 5;
std::bitset<32> bits = j;
std::cout << bits.count() << std::endl;
int k = 5;
int counter = 0;
while (k != 0) {
if ((k & 1) == 1) {
counter++;
}
k >>= 1;
}
std::cout << counter << std::endl;
return 0;
}
Let's look at this code. We can use bitset
or a simple loop to count the number of bits, and also, we can use the builtin function __builtin_popcount()
to do so. So what's the difference between them? If I use the builtin function, does it mean that I could get a better performance? Should I use the builtin function in my common c/c++ project?