Doubts about _mm_popcnt_u64()

Discussion of chess software programming and technical issues.

Moderator: Ras

Cardoso
Posts: 363
Joined: Thu Mar 16, 2006 7:39 pm
Location: Portugal
Full name: Alvaro Cardoso

Doubts about _mm_popcnt_u64()

Post by Cardoso »

Hi,
In my code I have:

Code: Select all

#define myPopCnt(bb) _mm_popcnt_u64(bb)
#define PopCnt(v) __popcnt64(v)
I have two doubts I would like to clear up.
1 - Both _mm_popcnt_u64() and __popcnt64() return a 64bit value but In my code I use 32bit ints to hold that value, is that safe or should I cast to an int to store that index?

Code: Select all

int index = myPopCnt(bb); 
or

Code: Select all

int index = (int)myPopCnt(bb); 
2 - Which is the fastest? _mm_popcnt_u64() or __popcnt64() ?
User avatar
Bo Persson
Posts: 257
Joined: Sat Mar 11, 2006 8:31 am
Location: Malmö, Sweden
Full name: Bo Persson

Re: Doubts about _mm_popcnt_u64()

Post by Bo Persson »

On a modern x86-64 system those intrinsics are the same, as the CPU has a hardware POPCNT instruction. Use whatever your compiler supports.

You can add a typecast if the compiler protests, as we all know that the result can never be above 64. So a cast would be safe.

As an alternative, in C++ you could use std::popcount that already returns an int.

https://en.cppreference.com/w/cpp/numeric/popcount