简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM