我有一个循环,这是我为特定功能耗费最多时间的循环,我想加快它的速度。目前,这个单个循环大约需要 400 毫秒,而其余函数的执行大约需要 610 毫秒。
代码是:
for ctr in xrange(N):
list1[ctr] = in1[ctr] - in1[0] - ctr * c1
list2[ctr] = in2[ctr] - in2[0] - ctr * c2
list3[ctr] = c3 - in1[ctr]
list4[ctr] = c4 - in2[ctr]
N 可以是 40,000 到 120,000 之间的任何值,是显示的所有列表(in1、in2、listN)的长度。
有谁知道一些 Python 技巧可以加快速度?我已经尝试使用 map 代替,因为我知道它会尝试编译为更高效的代码,但速度慢了大约 250 毫秒。
谢谢
最佳答案
假设 list1
、list2
等都是数字,考虑使用 numpy 数组而不是列表。对于大型整数或 float 序列,您会看到巨大的加速。
如果你走那条路,你上面的循环可以这样写:
ctr = np.arange(N)
list1 = n1 - n1[0] - ctr * c1
list2 = n2 - n2[0] - ctr * c2
list3 = c3 - ctr
list4 = c4 - ctr
作为计时的完整独立示例:
import numpy as np
N = 100000
# Generate some random data...
n1 = np.random.random(N)
n2 = np.random.random(N)
c1, c2, c3, c4 = np.random.random(4)
ctr = np.arange(N)
list1 = n1 - n1[0] - ctr * c1
list2 = n2 - n2[0] - ctr * c2
list3 = c3 - ctr
list4 = c4 - ctr
当然,如果您的 list1
、list2
等是非数字的(即除 float 或 int 之外的 python 对象列表),那么这将无济于事.
关于python - 优化 Python for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6831539/