简体   繁体   English

为什么python中的此循环运行速度越来越慢?

[英]Why does this loop in python runs progressively slower?

In this code, there is a 4-D array of 13x13 images. 在此代码中,有一个13D13图像的4维数组。 I would like to save each 13x13 image using matplotlib.pyplot . 我想使用matplotlib.pyplot保存每个13x13图像。 Here for debugging purposes, I limit the outer loop to 1. 在这里出于调试目的,我将外部循环限制为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. 保存4000张图像花费了20多个小时。 Why is it this slow? 为什么这么慢? If I limit the inner loop to the first 100 images, it takes about 1 minute. 如果我将内部循环限制为前100张图像,则大约需要1分钟。 So the whole thing should be completed in 40 minutes, not over 20 hours! 因此,整个过程应在40分钟内完成,而不是超过20小时! And I notice it seems to run progressively slower. 而且我注意到它的运行速度似乎越来越慢。

What you experience here is a memory leak: you keep creating instances of AxesImage objects (by repetitively calling plt.imshow ) to the moment they can't fit into RAM; 您在这里遇到的是内存泄漏:您一直在创建AxesImage对象的实例(通过重复调用plt.imshow )直到它们无法放入RAM plt.imshow and then the whole thing begins swapping to disk, which is incredibly slow. 然后整个事情开始交换到磁盘上,这非常慢。 To avoid memory leaks, you can either destroy AxesImage instance when you don't need it: 为了避免内存泄漏,您可以在AxesImage时销毁AxesImage实例:

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

Or, alternatively, you can create only one AxesImage , and then just change the data in it: 或者,您也可以仅创建一个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)
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM