OPEN CATALOG

Best practices for performance

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 examples #

Have a look at the following code:

float calc_div(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 calc_div(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.

Related resources #

References #