Counting bits in a ulong

Patrick Schluter Patrick.Schluter at bbox.fr
Thu Jun 4 07:42:07 UTC 2020


On Thursday, 4 June 2020 at 01:16:13 UTC, H. S. Teoh wrote:
> So recently I needed to implement a function to count the 
> number of 1
> bits in a ulong inside a (very) hot inner loop.  There's of 
> course the
> naïve method (`val` is the input ulong):
>
> [...]

You should try to use the popcnt instruction of the cpu (in asm 
or with intrinsics). It's at least 3 or 4 order of magnitude 
(i.e. between 1000 and 10000 times) faster than any of these 
tricks. I made the change last year in my work codebase since 
we've left the SPARC servers (they had a very slow implementation 
of popcount).
All modern CPU's have the instruction.


More information about the Digitalmars-d mailing list