Issue #
The pow
mathematical function is computationally expensive and in many cases can be replaced by faster mathematical operations.
Actions #
Replace the pow
invocation by the corresponding calculation involving multiplications, divisions and/or square roots.
Relevance #
Function pow
is commonly used in scientific computations. In general, it is an expensive function. However, in some cases when the value of exponent is known at compile time, its runtime can be greatly reduced by replacing it with a combination of multiplications, divisions and square roots.
Note
Some compilers under some circumstances (e.g. relaxed IEEE 754 semantics) can do this optimization automatically. However, doing it manually will guarantee best performance across all the compilers.
Code examples #
The following code invokes pow
to calculate x
to the power of 1.5
:
#include <math.h>
float example(float *a, float x) {
for (int i = 0; i < 10; ++i) {
a[i] = pow(x, 1.5);
}
}
This can also be accomplished by multiplying x
by its square root, which is faster:
#include <math.h>
float example(float *a, float x) {
for (int i = 0; i < 10; ++i) {
a[i] = x * sqrt(x);
}
}