【发布时间】:2018-07-29 09:10:11
【问题描述】:
我正在尝试模拟抛硬币和利润并在 matplotlib 中绘制图表:
from random import choice
import matplotlib.pyplot as plt
import time
start_time = time.time()
num_of_graphs = 2000
tries = 2000
coins = [150, -100]
last_loss = 0
for a in range(num_of_graphs):
profit = 0
line = []
for i in range(tries):
profit = profit + choice(coins)
if (profit < 0 and last_loss < i):
last_loss = i
line.append(profit)
plt.plot(line)
plt.show()
print("--- %s seconds ---" % (time.time() - start_time))
print("No losses after " + str(last_loss) + " iterations")
最终结果是
--- 9.30498194695 seconds ---
No losses after 310 iterations
为什么运行这个脚本需要这么长时间?如果我将 num_of_graphs 更改为 10000,脚本永远不会完成。
你会如何优化它?
【问题讨论】:
-
可能会有更好的答案,但我会做的第一件事是因为你知道
line会有多大,那就是使用 numpy 并预先分配你的数组。line = np.zeros((2000,))在任一循环外,然后是line[i] = profit在第二个循环内。分配一次,然后继续重写。
标签: python performance matplotlib