What's the fastest method to return the position of the least significant bit set in an integer in Python 3?

断了今生、忘了曾经 提交于 2019-12-11 10:10:16

问题


I'm curious to find what the fastest algorithm is for returning the position of the least significant bit set in an integer in Python 3.

Are there algorithms faster than this one in Python 3? Any enhancements one could use to speed things up?

def lsb(n):
    temp = n & -n
    pos = -1
    while temp:
        temp >>= 1
        pos += 1
    return(pos)

回答1:


summarizing, since this is for python3 and so not an exact duplicate of return index of least significant bit in Python (although there are other applicable answers there, some perhaps better):

jcomeau@aspire:/tmp$ cat lsb.py 
#!/usr/bin/python3
import math, sys
def lsb0(n):
    temp = n & -n
    pos = -1
    while temp:
        temp >>= 1
        pos += 1
    return(pos)
def lsb1(n):
    return int(math.log2(n & -n))
def lsb2(n):
    return (n & -n).bit_length() - 1
if __name__ == '__main__':
    algorithm = sys.argv[1]
    lsb = eval('lsb{n}'.format(n = algorithm))
    for n in range(1, 1000000):
        #print(lsb(n))
        lsb(n)

and as aaron_world_traveler observed, Mark Dickinson's answer is the fastest.

jcomeau@aspire:/tmp$ time lsb.py 0

real    0m2.506s
user    0m2.472s
sys 0m0.024s
jcomeau@aspire:/tmp$ time lsb.py 1

real    0m3.336s
user    0m3.284s
sys 0m0.040s
jcomeau@aspire:/tmp$ time lsb.py 2

real    0m1.646s
user    0m1.636s
sys 0m0.008s


来源:https://stackoverflow.com/questions/34166566/whats-the-fastest-method-to-return-the-position-of-the-least-significant-bit-se

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