【发布时间】:2012-02-15 15:50:31
【问题描述】:
以下是测试代码,我的实际代码看起来几乎相似,其中我使用原始矩阵而不是随机生成。如何优化这个嵌套的 for 循环。我知道这在 python 中是可能的,但我无法这样做。
import time
import numpy as np
a = 1000
b = 500
sum2,sum3,sum4 = 0
t0 = time.time()
x = np.random.random(a*a).reshape([a,a])
for outer1 in xrange(0,a):
for inner1 in xrange(0,b):
for outer2 in xrange(0,a):
for inner2 in xrange(0, a):
sum2 += x[outer2][inner2] #this is not the only operation I have
for outer3 in xrange(0,a):
for inner3 in xrange(0, a):
sum3 += x[outer3][inner3] #this is not the only operation I have
for outer4 in xrange(0,a):
for inner4 in xrange(0, a):
sum4 += x[outer4][inner4] #this is not the only operation I have
print time.time() - t0
print 'sum2: '+str(sum2)+' sum3: '+str(sum3)+' sum4: '+str(sum4)
我正在使用 python 2.7。 谢谢。
【问题讨论】:
-
您所做的额外计算对优化代码的方式有很大影响。而且,也更有可能是任何瓶颈的原因,而不是这些总和。
标签: python performance optimization for-loop nested-loops