pyplot:创建热图真的很慢
我有一个循环执行主体大约 200 次。在每次循环迭代中,它都会进行复杂的计算,然后作为调试,我希望生成 NxM 矩阵的热图。但是,生成此热图的速度慢得令人难以忍受,并且会显着减慢本来就很慢的算法。
我的代码是这样的:
import numpy
import matplotlib.pyplot as plt
for i in range(200):
matrix = complex_calculation()
plt.set_cmap("gray")
plt.imshow(matrix)
plt.savefig("frame{0}.png".format(i))
来自 numpy 的矩阵并不大 --- 300 x 600 的双精度数。即使我不保存图形而是更新屏幕上的绘图,速度也会更慢。
当然,我一定是在滥用 pyplot。 (Matlab 可以做到这一点,没问题。)如何加快速度?
I have a loop that executes the body about 200 times. In each loop iteration, it does a sophisticated calculation, and then as debugging, I wish to produce a heatmap of a NxM matrix. But, generating this heatmap is unbearably slow and significantly slow downs an already slow algorithm.
My code is along the lines:
import numpy
import matplotlib.pyplot as plt
for i in range(200):
matrix = complex_calculation()
plt.set_cmap("gray")
plt.imshow(matrix)
plt.savefig("frame{0}.png".format(i))
The matrix, from numpy, is not huge --- 300 x 600 of doubles. Even if I do not save the figure and instead update an on-screen plot, it's even slower.
Surely I must be abusing pyplot. (Matlab can do this, no problem.) How do I speed this up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将
plt.clf()
放入循环中以清除当前图形:如果不这样做,循环会减慢,因为机器会努力为图形分配越来越多的内存。
Try putting
plt.clf()
in the loop to clear the current figure:If you don't do this, the loop slows down as the machine struggles to allocate more and more memory for the figure.
我认为这更快一点:
plt.imshow
调用gca
,后者调用gcf
,检查是否有数字;如果没有,它就会创建一个。通过首先手动实例化图窗,您不需要执行所有这些操作。I think this is a bit faster:
plt.imshow
callsgca
which callsgcf
which checks to see if there is a figure; if not, it creates one. By manually instantiating the figure first, you do not need to do all that.