Why is this loop in python slower?

This code has a 4-dimensional array of 13x13 images. I would like to save each 13x13 image using matplotlib.pyplot. Here, for debugging purposes, I limit the outer loop to 1.

#fts is a numpy array of shape (4000,100,13,13)
no_images = 4000
for m in [1]:  
    for i in range(no_images):
        print i,
        fm = fts[i][m]
        if fm.min() != fm.max():
            fm -= fm.min()
            fm /= fm.max()  #scale to [0,1]
        else:
            print 'unscaled'
        plt.imshow(fmap)
        plt.savefig('m'+str(m)+'_i'+str(i)+'.png')

Saving 4000 images took more than 20 hours. Why is it so slow? If I limit the inner loop to the first 100 images, it will take about 1 minute. Thus, all this should be completed in 40 minutes, not in 20 hours! And I notice that it works more slowly.

+4
source share
1 answer

, , : AxesImage ( plt.imshow) , ; , . , AxesImage, :

...
image = plt.imshow(fmap)
plt.savefig('m'+str(m)+'_i'+str(i)+'.png')
del(image)

, , AxesImage, :

...
image = None
for m in [1]:  
    for i in range(no_images):
        ...
        if image is None:
             image = plt.imshow(fmap)
        else:
             image.set_data(fmap)
        ...
+4

Source: https://habr.com/ru/post/1613447/


All Articles