我有以下代码。原则上,它需要执行2^6 * 1000 = 64000次迭代,这是一个相当小的数量。但在我的电脑上需要9秒钟,而我想至少运行n = 15。
from __future__ import division
import numpy as np
import itertools
n=6
iters = 1000
firstzero = 0
bothzero = 0
for S in itertools.product([-1,1], repeat = n+1):
for i in xrange(iters):
F = np.random.choice(np.array([-1,0,0,1], dtype=np.int8), size = n)
while np.all(F ==0):
F = np.random.choice(np.array([-1,0,0,1], dtype=np.int8), size = n)
FS = np.convolve(F,S, 'valid')
if (FS[0] == 0):
firstzero += 1
if np.all(FS==0):
bothzero += 1
print "firstzero", firstzero
print "bothzero", bothzero
这个是否可能大幅度加速,还是需要用C重写?
分析表明它的大部分时间都花在了
258003 0.418 0.000 3.058 0.000 fromnumeric.py:1842(all)
130003 1.245 0.000 2.907 0.000 {method 'choice' of 'mtrand.RandomState' objects}
388006 2.488 0.000 2.488 0.000 {method 'reduce' of 'numpy.ufunc' objects}
128000 0.731 0.000 2.215 0.000 numeric.py:873(convolve)
258003 0.255 0.000 2.015 0.000 {method 'all' of 'numpy.ndarray' objects}
258003 0.301 0.000 1.760 0.000 _methods.py:35(_all)
130003 0.470 0.000 1.663 0.000 fromnumeric.py:2249(prod)
644044 1.483 0.000 1.483 0.000 {numpy.core.multiarray.array}
130003 0.164 0.000 1.193 0.000 _methods.py:27(_prod)
258003 0.283 0.000 0.624 0.000 numeric.py:462(asanyarray)
n=15
将始终比n=6
慢2^15 / 2^6 = 2^9
倍,因此为了保持相同的时间,实际上需要512倍的加速。 - luk32