【发布时间】:2012-11-02 20:09:15
【问题描述】:
检查我的以下代码;它是在 python 中实现的 sigma_2 函数(使用粗筛)的一部分,它是除数函数之一http://mathworld.wolfram.com/DivisorFunction.html
from time import time
from itertools import count
import numpy
def sig2(N, nump=False):
init = time()
#initialize array with value=1 since every positive integer is divisible by 1
if nump:
print 'using numpy'
nums = numpy.ones((N,), dtype=numpy.int64)
else:
nums = [1 for i in xrange(1, N)]
#for each number n < N, add n*n to n's multiples
for n in xrange(2, N):
nn = n*n
for i in count(1):
if n*i >= N: break
nums[n*i-1] += nn
print 'sig2(n) done - {} ms'.format((time()-init)*1000)
我尝试了不同的值,但使用 numpy 非常令人失望。
2000 年:
sig2(n) done - 4.85897064209 ms
took : 33.7610244751 ms
using numpy
sig2(n) done - 31.5930843353 ms
took : 55.6900501251 ms
对于 200000:
sig2(n) done - 1113.80600929 ms
took : 1272.8869915 ms
using numpy
sig2(n) done - 4469.48194504 ms
took : 4705.97100258 ms
它继续,我的代码不是真正可扩展的 - 因为它不是 O(n),但是使用这两个以及除这两个结果之外,使用 numpy 会导致性能问题。 numpy 不应该比 python 列表和字典更快吗?这就是我对 numpy 的印象。
【问题讨论】:
-
我看不到你的函数是如何实现除数函数的。返回值是多少?
-
它返回 sigma_2 匹配给定条件的数字列表。这里只有一小部分代码...