Performance of pow in C++
It is common best practice to use a*a
instead of pow(a, 2)
, as the pow
function is relatively slow. While this method could in principle be also used
for larger integers as exponents, this quickly becomes unreadable and error prone.
However, there are two possible solutions for this.
If the exponent is known during compiletime, a templates can be used:
This will give a speedup of ~10x or more over the pow
function.
If the exponent is not known during compiletime, still a speedup of ~1.7 over the pow
function can be achieved using a loop in a function like: