Last active
July 7, 2019 12:05
-
-
Save isilence/c3395728159a8c602fc6e71ea03318bb to your computer and use it in GitHub Desktop.
Fast most significant bit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline unsigned long msb_intrin(unsigned long x) | |
{ | |
const int zs = __builtin_clzl(x); | |
return 1ul << (sizeof(x) * CHAR_BIT - zs - 1); | |
} | |
inline unsigned long msb_fast(unsigned long x) | |
{ | |
int bit_size = sizeof(x) * CHAR_BIT; | |
#pragma unroll | |
for (int j = 0; (1 << j) < bit_size; ++j) | |
x |= x >> (1 << j); | |
return x - (x >> 1); | |
} | |
inline unsigned long msb_bitset(unsigned long x) | |
{ | |
unsigned long t; | |
do { | |
t = x; | |
x &= x - 1ul; | |
} while (x != 0ul); | |
return t; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
msb_intrin: O(1) 0.001 ms | |
msb_fast: O(log(log(num))) 305.606 ms | |
msb_avg: O(# of set bits) 1202.82 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment