python - 为什么在循环调用时 plt.savefig() 性能会下降?

标签 python image performance matplotlib plot

我写了下面的代码来测试matplotlib的savefig()函数的性能:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
import time

for i in xrange(10):

    init = time.time()
    x = rand(100)
    y = rand(100)
    t_init=time.time()-init

    init = time.time()
    ax = plt.axes()
    t_axes=time.time()-init

    init = time.time()
    num, _, _ = np.histogram2d(x,y)
    t_hist = time.time()-init

    init = time.time()
    ax.imshow(num, extent=[-.5,.5,-.5,.5], interpolation="bicubic")
    t_imshow = time.time()-init

    init = time.time()
    t = ax.text(i*.1,.1, "Value ="+str(i))
    plt.savefig("test/"+str(i)+".png")
    t.remove()
    t_savefig = time.time()-init

    print t_init, t_axes, t_hist, t_imshow, t_savefig

出乎意料的是,savefig() 的性能随着每次迭代而下降,如下表最后一列所示:

t_inint           t_axes            t_hist            t_imshow         t_savefig
4.10079956055e-05 0.114418029785    0.000813007354736 0.00125503540039 0.668319940567
2.28881835938e-05 0.000143051147461 0.00158405303955  0.00119304656982 0.297608137131
1.90734863281e-05 0.000148057937622 0.000726938247681 0.0012149810791  0.356621026993
2.31266021729e-05 0.0001380443573   0.000706911087036 0.0011830329895  0.37288403511
2.28881835938e-05 0.000149011611938 0.000706195831299 0.00119686126709 0.416905879974
2.00271606445e-05 0.000148057937622 0.000704050064087 0.00118589401245 0.505565881729
2.19345092773e-05 0.000140905380249 0.000710010528564 0.00121307373047 0.494667053223
2.09808349609e-05 0.000147819519043 0.000703096389771 0.00119400024414 0.5519759655
2.09808349609e-05 0.000139951705933 0.000716209411621 0.0011990070343  0.624140977859
3.2901763916e-05  0.000142097473145 0.000709056854248 0.00120401382446 0.634006023407

是什么导致 savefig() 变慢?我怎样才能避免这种行为? 谢谢。

最佳答案

你需要清除绘图之间的轴,添加 plt.cla() 就可以了,有一个很棒的 stackoverflow post about clearing figures值得一读。

关于python - 为什么在循环调用时 plt.savefig() 性能会下降?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18829472/

相关文章:

java - 如何确定 Java 应用程序速度慢的原因

python - Google Analytics API 过滤器返回的值过于严格

python - 无法将 proto 文件构建到描述符池中

python - numpy:替换 recarray 中的值

python - point 参数对 matplotlib 中的 fiddle 图有什么作用

javascript - 客户端下载的图片格式

performance - 解决递归问题 T(n) = 4T(n/4) + 3log n

ios - 如何使用PHPhotoKit将CLLocation的GPS信息写入UIImage?

wpf - Crystal Reports VS2010如何在不同页面获取不同的图片

performance - 如何以最大性能标准化 CUDA 中的矩阵列?