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

时间:2013-09-16 13:39:25

标签: 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()减速的原因是什么?我该如何避免这种行为? 谢谢。

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

如果你在迭代之间进行plt.clf(),那么时间并没有真正增加。 我的猜测是,在你之前的轴上过度绘图(累积它们)之前,这会导致更长的保存。