Better way to find the powers of 2

北城余情 提交于 2019-12-13 07:58:40

问题


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?


回答1:


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.)




回答2:


<< 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


来源:https://stackoverflow.com/questions/27035753/better-way-to-find-the-powers-of-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!