+ 2
Which is theoretically faster?
2<<N or pow(2,N)?
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
+ 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.
+ 1
you are talking about operator vs function...
I guess most of the time an operator will be faster
0
so, we could do 2<<31 instead of INT_MAX?
0
2<<31 is 32 bit zero, 1<<31 is signed min, !(1<<31) is signed max
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?