Hasty Briefsbeta

Bilingual

Matt Godbolt's blog

15 hours ago
  • The population count operation counts the number of one bits in a binary value and is useful in areas like data compression, cryptography, and chess.
  • A common method to count bits is looping 64 times, but a more efficient approach uses a trick to clear the lowest set bit by ANDing the value with (value - 1).
  • Modern compilers like GCC and Clang can optimize a population count loop into a single 'popcnt' instruction when using appropriate architecture flags like -march=westmere.
  • The compiler's loop deletion pass recognizes the functional equivalence of the loop and replaces it with a single instruction, though using std::popcount in C++ is recommended for clarity.
  • Some CPU architectures may have performance quirks, such as a false dependency bug in Sandy Bridge requiring an extra 'xor eax, eax' before 'popcnt'.