I wrote the following code to test the performance of matplotlib's savefig()function:
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
Unexpectedly, the performance of savefig() decreases with every iteration, as shown in the last column of the following table:
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
What causes savefig() to slow down? How can I avoid this behavior?
Thank you.
You need to clear your axis between plots, adding plt.cla() will do the trick, there is a great stackoverflow post about clearing figures that is worth a read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With