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

3

我编写了以下代码来测试 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个回答

10

3
如果您在迭代之间执行plt.clf(),那么时间不会真正增加。 我猜想在此之前你已经重叠了上一个坐标轴(累积它们),这导致了更长的savefig。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接