python循环整数组中的位

时间:2018-12-10 16:00:58

标签: python python-3.x

在python 3中,我编写了一个生成器,用于一次循环5位整数:

def int_loop(x):
    while(x):
        yield x%32
        x//=32

这有效,但是有点慢。

我的问题是:是否有一个预先存在的模块,它的执行速度更快?

2 个答案:

答案 0 :(得分:2)

我不确定您所说的“太慢”是什么意思,但由于您知道x in [0, 100000]

def loop5b(x):
    g1 = (x & 0b00000000000011111)
    g2 = (x & 0b00000001111100000) >> 5
    g3 = (x & 0b00111110000000000) >> 10
    g4 = (x & 0b11000000000000000) >> 15

    if g4:
        return g1, g2, g3, g4
    if g3:
        return g1, g2, g3
    if g2:
        return g1, g2
    if g1:
        return g1,
    return ()

与您的while循环相比,这节省了大约'0.05'秒(对于x范围为(0,100000),则为'0.052'秒,而'0.098'秒)。我敢肯定,您可以用Cython编写该文章来做得更好。但真正的问题是:真的值得吗?记住:“过早的优化是万恶之源”〜Donald Knuth

答案 1 :(得分:1)

此版本

def my_5_bits(n):
    m = 0b11111
    while n:
        yield n & m
        n >>= 5

一致地节省了一些时间:

n=0b1111010101010111010011010110010111011110101010101110100110101100101110
%timeit list(my_5_bits(n))
1.76 µs ± 8.15 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

反对

%timeit list(int_loop(n))
1.98 µs ± 33.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)