首页 > 解决方案 > 提高循环速度

问题描述

我有 100 万个循环要做。无论如何处理这个(和一般的python循环)更快吗?

import numpy
#in a population of 1000 individuals of the same species, one individual has an advantageous mutation
#before, the average quantity of newborns per each 2 individuals per generation was 2 (no average change in pop)

popN, popM= 999, 1
period= 1000

reproductionDistN=[0.1, 0.2, 0.41, 0.19, 0.1] #expected value= 1.95
reproductionDistM=[0.1, 0.2, 0.39, 0.21, 0.1] #expected value= 2.05

def reproduce(pop, reproductionDist):
    newborns=numpy.random.choice(numpy.arange(0,5), p=reproductionDist) #numpy.arange(0,5)=[0, 1, 2, 3, 4]
    pop+=newborns
    return pop

for t in range(period):
    for n in range(popN): popN=reproduce(popN, reproductionDistN)  
    for m in range(popM): popM=reproduce(popM, reproductionDistM) 

print("Population of N:",popN)
print("Population of M:",popM)

标签: pythonperformanceloops

解决方案


用 numpy 数组操作替换 python 循环通常有助于提高性能。

在您的示例中,您有效地做到了

pop = 100  # for example

for i in range(pop):
    pop += np.random.choice(5, p=reproductionDistM)

在每次迭代中。

所有采样和求和都可以在 numpy 中完成,无需循环:

pop = 100
pop += np.random.choice(5, p=reproductionDistM, size=pop).sum()

在我的机器上,这提供了很大的加速(多少取决于 的值pop,例如 100 左右)。

另一方面,如果数组很大,这会浪费大量 RAM。在这种情况下,我经常发现通过批量使用 numpy 来平衡速度和 RAM 是很实用的。


推荐阅读