python - 提高循环速度
问题描述
我有 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)
解决方案
用 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 是很实用的。
推荐阅读
- node.js - 确认响应发送太晚;NodeJS Express 异步响应
- spring - 在 Spring Boot 上以编程方式设置 Ehcache 的持久化目录
- solr - solr 最后用通配符搜索
- python - ModuleNotFoundError:没有名为“tweepy”的模块
- android - 科尔多瓦 bluetoothSerial.discoverUnpaired 不会在 android 10 中发出值
- windows - 是否有任何方法可以使用 shell 命令获取 Windows 设备中所有已安装应用程序的详细信息
- ms-access - 使用 MS Access 查询(BOM 资源管理器的排序)
- sql - 如何在 SQL Server SQL Query 中进行多个左连接
- javascript - JavaScript 循环将数据附加到 formData - 递增变量显示与 formData 中的每个循环相同
- kivy - 在 Kivy 中使用构建器