PWR046: Replace two divisions with a division and a multiplication
Issue
Divisions are expensive operations on modern hardware, so replacing divisions with cheaper operations often results in speed boost.
Actions
Replace double division with a division and a multiplication.
Relevance
Double divisions can be replaced with a division and multiplication, according to the following patterns:
-
(a / b) / c = a / (b * c)
. -
a / (b / c) = (a * c) / b
.
Code example
Have a look at the following code:
float example(float a, float b, float c) {
return a / b / c;
}
The expression a / b / c
can be rewritten with a single division and a
multiplication, like this:
float example(float a, float b, float c) {
return a / (b * c);
}
note
The compiler does this optimization automatically when
-funsafe-math-optimizations
compilation flag is provided.