Skip to content Skip to sidebar Skip to footer

Better Way To Find The Powers Of 2

I am new to python. Is 1 << n is always better than 2 ** n? Why or Why not? Are there any better ways to find the powers of 2?

Solution 1:

<< and ** works almost same when compare to time complexity, result can be seen, pow works faster when values are small then these but for large values it works slow

In [108]: %timeit pow(2, 2)
10000000 loops, best of 3: 127 ns per loop

In [104]: timeit 1<<2
10000000 loops, best of 3: 23.2 ns per loop

In [105]: timeit 2**2
10000000 loops, best of 3: 24.5 ns per loop


In [111]: %timeit  1<<10
10000000 loops, best of 3: 23.9 ns per loop

In [112]: %timeit  2**10
10000000 loops, best of 3: 23.5 ns per loop

In [113]: %timeit pow(2, 10)
10000000 loops, best of 3: 167 ns per loop

In [114]: %timeit  1<<10000
10000000 loops, best of 3: 23.5 ns per loop

In [115]: %timeit  2**10000
10000000 loops, best of 3: 23.9 ns per loop

In [116]: %timeit pow(2, 10000)
10000 loops, best of 3: 27.7 µs per loop

Solution 2:

An important programming tenet: don't over-optimise prematurely.

Given that 1 << n will be performed in integer arithmetic which significantly limits the results space, the fastest way would be to precompute them and use a lookup table (e.g. a simple array). For a 64 bit unsigned integral types such a table would only have 64 entries.

(In C++ you could even evaluate them at compile time with a bit of template trickery.)


Post a Comment for "Better Way To Find The Powers Of 2"