+ 2

Which is theoretically faster?

2<<N or pow(2,N)?

17th Jul 2016, 11:29 PM
_Geometry dash_ _Roh_ (AKA NovaRate0315)
_Geometry dash_ _Roh_ (AKA NovaRate0315) - avatar
6 Réponses
+ 2
the 2<<N is faster as the C++ compiler can make direct optimization on it when writing the assembly code. on the other hand the pow(2, N) is a function meaning that the compiler potentialy compiles an algorithm, which will probably be called in the assembly level, making it both slower because of the call and because this compiles an algorithm, not a simple operation... but on today's CPUs you don't really see a difference :D
18th Jul 2016, 12:02 AM
Itay Almog
Itay Almog - avatar
+ 2
I would assume 2<<N is much faster as bitshift operations on integers are superfast and pow works on a floats. Classically, pow would use a Taylor series which requires summation of the terms in the series via loop. As long as this is not implemented in hardware or an optimized version for 2<<N is implemented by the standard library, the difference will be huge. Btw, the bitshift might also work on floats... As the exponent part could be shifted as well to achieve the same result as on integers.
18th Jul 2016, 1:02 AM
Stefan
Stefan - avatar
+ 1
you are talking about operator vs function... I guess most of the time an operator will be faster
18th Jul 2016, 4:00 AM
Mukul Kumar
Mukul Kumar - avatar
0
so, we could do 2<<31 instead of INT_MAX?
18th Jul 2016, 4:46 AM
_Geometry dash_ _Roh_ (AKA NovaRate0315)
_Geometry dash_ _Roh_ (AKA NovaRate0315) - avatar
0
2<<31 is 32 bit zero, 1<<31 is signed min, !(1<<31) is signed max
18th Jul 2016, 9:30 AM
Marcin Lesniewski
Marcin Lesniewski - avatar
0
@Mukul: You are confusing what operators and functions are. In C++ you can overload an operator by defining it's function. Thus, operators *are* functions... the only question is: can the function be reduced to one bitshift assembler operation?
18th Jul 2016, 9:55 AM
Stefan
Stefan - avatar