0

Which expression is fast?

z= x*x or z= pow(x,2)

30th Nov 2017, 2:43 PM
Vijay
Vijay - avatar
5 Respostas
+ 4
In this simple case I would guess (not tested!) that x*x is faster than pow(x, 2). The reason being that pow(..) is actually a function call, and that entails some overhead with regard to pushing the function onto the stack frame, copying the arguments onto the stack frame, etc. Then more overhead for setting new SP, etc. Where as the x*x is a very simple expression which will actually be executed directly from 2 registers. But this may not necessarily be true in all cases - it will depend on the particular expression!
30th Nov 2017, 3:08 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 2
With optimizations enabled this generates the same assembly, meaning they run at the same speed. I did a speed test, just because I wanted to know how much slower the pow( x, 2 ) would be, and without optimizations enabled the x * x version was many times faster. Running each test 100.000.000 times, x * x finished in 0.214 seconds. pow( x, 2 ) finished in 2.041 seconds.
30th Nov 2017, 3:13 PM
Dennis
Dennis - avatar
+ 1
In most compilers pow is guaranteed to be inlined with optimization enabled, resulting in the same exact assembly and no performance difference. But x * x is always guaranteed to be as equal or faster. So if it truly matters, use x * x
30th Nov 2017, 3:15 PM
aklex
aklex - avatar
+ 1
@Dennis & @aklex - good point! I forgot about optimization. Yes, with inlining there will be no function call, so we are in fact just comparing expressions.
30th Nov 2017, 3:39 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Yeah, x*x is faster than pow(x,2). I just checked by using Chrono in debug mode.
30th Nov 2017, 3:24 PM
Vijay
Vijay - avatar