python - 优化 Python for 循环

标签 python optimization

我有一个循环,这是我为特定功能耗费最多时间的循环,我想加快它的速度。目前,这个单个循环大约需要 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 毫秒。

谢谢

最佳答案

假设 list1list2 等都是数字,考虑使用 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

当然,如果您的 list1list2 等是非数字的(即除 float 或 int 之外的 python 对象列表),那么这将无济于事.

关于python - 优化 Python for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6831539/

相关文章:

Python datetime.strptime() 占用大量 CPU 时间

python - 使用 MySQL 在 Python 中进行高效的子字符串搜索

python - 如何在h5py中指定自定义压缩过滤器

c++ - LLVM 编译器优化导致 bool 类成员的逻辑中断

C读取所有输入一次优化

java - 遗传算法 : Request optimization

algorithm - BFGS 对凸超参数化问题的收敛性

python - 文本提取中的断词, Lxml Xpath

python - 为什么我不能在 Python 上单击并拖动圆圈?

python - gremlin-python - 无法添加边缘属性