I ran a few benchmarks, using the average as reported by GetTickCount over 5 runs of 1,000,000 randomly generated numbers each.
5th place was Delfi's trunc(power(2,trunc(log2(number)))); with a dreadful 146.80 ms average
4th place was my code ops: with a 40.60ms average...
3rd place was jdarling's original code! Well Done! with an average of 25.00ms.
2nd place was Lifepower's NextPowerOfTwo() at 18.80ms
(which returns the next highest power if given a power, so 1024 returns 2048...)
And the winner is... Cairnswm! with an average of just 6.20ms, calling the PreparePowerTwos function once at the start of every run.
I guess I stand corrected. Lookups are not really faster in this case unless you go all the way!For a real multiply, yes. But a multiply with 2 wil be translated to a "add register,register", which is one of the cheapest operations in the CPU
Bookmarks