小编Moo*_*rsy的帖子

为什么我的Eratosthenes筛子使用整数比使用布尔值更快?

我写了一个简单的Eratosthenes筛子,它使用了一个列表,如果不是素数则将它们变成零,如下:

def eSieve(n): #Where m is fixed-length list of all integers up to n
    '''Creates a list of primes less than or equal to n'''
    m = [1]*(n+1)
    for i in xrange(2,int((n)**0.5)+1):
        if m[i]:
            for j in xrange(i*i,n+1,i):
                m[j]=0
    return [i for i in xrange(2,n) if m[i]]
Run Code Online (Sandbox Code Playgroud)

我测试了它运行的速度%timeit并获得:

#n: t
#10**1: 7 ?s
#10**2: 26.6 ?s
#10**3: 234 ?s
#10**4: 2.46 ms
#10**5: 26.4 ms
#10**6: 292 ms
#10**7: 3.27 s
Run Code Online (Sandbox Code Playgroud)

我假设,如果我改变[1]并且0使用布尔值,它会跑得更快......但它恰恰相反:

#n: t …
Run Code Online (Sandbox Code Playgroud)

python performance boolean cpython python-2.7

13
推荐指数
1
解决办法
266
查看次数

标签 统计

boolean ×1

cpython ×1

performance ×1

python ×1

python-2.7 ×1