在Python 3中返回整数中最低有效位的位置的最快方法是什么? [英] What's the fastest method to return the position of the least significant bit set in an integer in Python 3?

查看:189
本文介绍了在Python 3中返回整数中最低有效位的位置的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道最快的算法是什么,它返回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.

是否有比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)

推荐答案

总结,因为这是针对python3的,因此与

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)

,并且观察到 aaron_world_traveler

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

这篇关于在Python 3中返回整数中最低有效位的位置的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆