Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

4
  • 9
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf, and congratulations on a stellar first post! \$\endgroup\$ Commented Feb 27, 2016 at 19:34
  • \$\begingroup\$ Consider using -O3 -march=native. Your CPU supports the popcnt instruction, and compilers can sometimes recognize some pure C implementations of it and compile to the single instruction. (Or better, use __builtin_popcountll on GNU C, like Dennis's answer). \$\endgroup\$ Commented Dec 17, 2016 at 19:07
  • \$\begingroup\$ -march=native on your Haswell CPU will also enable BMI2 for more efficient variable-count shift instructions. (SHLX instead of the legacy SHL that needs count in cl.) The OP's AMD Piledriver CPU doesn't have BMI2, but it does have popcnt. But AMD CPUs run variable-count SHL faster than Intel CPUs, so compiling with BMI2 while tuning might still be appropriate. Piledriver is pretty different from Haswell as far as micro-optimizations go, but asking for -march=native is good \$\endgroup\$ Commented Dec 17, 2016 at 19:11
  • \$\begingroup\$ We now have JavaScript version that performs 20 times better - see my answer :) \$\endgroup\$ Commented Oct 22, 2021 at 8:28