Beating a dead horse here. A typical (and quick) way to do integer degrees in C is this classic:
int64_t ipow(int64_t base, int exp){ int64_t result = 1; while(exp){ if(exp & 1) result *= base; exp >>= 1; base *= base; } return result; }
However, it took me an integer compilation time, so I went ahead and did a recursive implementation using constexpr:
constexpr int64_t ipow_(int base, int exp){ return exp > 1 ? ipow_(base, (exp>>1) + (exp&1)) * ipow_(base, exp>>1) : base; } constexpr int64_t ipow(int base, int exp){ return exp < 1 ? 1 : ipow_(base, exp); }
The second function is designed to process indicators less than 1 in a predictable way. Passing exp<0 is an error in this case.
Recursive version 4 times slower
I generate a vector from 10E6 random bases and metrics in the range of [0.15] and the time of both algorithms on the vector (after doing a non-urgent run to try to remove any caching effects). Without optimization, the recursion method is twice as fast as the loop. But with -O3 (GCC), the cycle is 4 times faster than the recursion method.
My question to you guys is this: Can someone come up with a faster ipow () function that handles exponent and base 0 and can be used as constexpr ?
(Disclaimer: I don't need a fast ipow, I'm just interested to see what smart people have to offer).
c ++ optimization c ++ 11 recursion constexpr
Emily L.
source share