我写了以下代码来测试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()
减速的原因是什么?我怎样才能避免这种行为?谢谢你。