Depending on this question Floating point division vs floating point multiplication. Division is slower than multiplication due to some reasons.
Will the compiler, usually, replace division by multiplication if it is possibe?
For example:
float a; // During runtime a=5.4f float b = a/10.f;
Will it be:
float a; // During runtime a=5.4f float b = a*0.1f;
If it is considered a compiler dependable question, I am using VS2013 default compiler. However, it would be nice if I got a generic answer (theoretical validity of this optimization)
After understanding what this code does, I knew this is a compiler optimization - This code simply performs a division operation without using the 'div' instruction. 'div' is an expensive operation for the CPU - even more than multiplication.
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.
Multiplication is faster than division.
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.
No, the compiler is not allowed to do that for the general case: the two operations could produce results that are not bit-identical due to the representation error of the reciprocal.
In your example, 0.1
does not have an exact representation as float
. This causes the results of multiplication by 0.1
and division by 10
to differ:
float f = 21736517; float a = f / 10.f; float b = f * 0.1f; cout << (a == b) << endl; // Prints zero
Demo.
Note: As njuffa correctly notes in the comment below, there are situations when the compiler could make some optimizations for a wide set of numbers, as described in this paper. For example, multiplying or dividing by a power of two is equivalent to addition to the exponent portion of the IEEE-754 float
representation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With