for 循环中的 Matplotlib 和 python 垃圾收集

Dav*_*ide 5 python garbage-collection memory-management matplotlib

我需要使用 Python 和 Matplotlib 导出多个图,但我在内存管理方面遇到了问题。

我在 Windows 中使用 Jupyter Notebook,代码的结构如下面的工作示例所示。基本上,我在几年的时间内每天生成一个情节。

根据内存使用情况,我可以看到,通常在前 4 个“月”内,内存使用量相当稳定,但随后每个“天”都会增加超过 15MB。对于完整的代码,这会导致内存错误。

我尝试plt.close()按照此处的建议使用。我也尝试过plt.close(fig)plt.close('all')并手动删除一些变量del。最后我gc.collect进入了循环。似乎没有任何效果。

import numpy as np
import matplotlib.pyplot as plt
import gc

sz = 1000
i=0
for year in [2014,2015,2016,2017]:
    for month in [1,2,3,4,5,9,10,11,12]:
        for day in range(1,30):

            # Plot
            fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2,figsize=(14,10))

            x1 = np.arange(1,sz+1,1)
            y1 = np.random.random(sz)
            ax1.scatter(x1,y1)
            ax2.scatter(x1,y1)
            ax3.scatter(x1,y1)
            ax4.scatter(x1,y1)

            filename = 'test/test_output{}{}{}.png'.format(year,month,day)
            plt.tight_layout()
            plt.savefig(filename, bbox_inches='tight')

            #plt.close(fig)            
            #plt.close('all')
            plt.close()

            del x1, y1, ax1, ax2, ax3, ax4, fig

            # counter
            i=i+1

        # Monthly operations
        print(filename,i)
        gc.collect()

# Triggered outside the loops
gc.collect()
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我中断代码(或者我等待“内存错误”发生)然后我手动运行gc.collect,内存会立即被清除。

为什么gc.collect在嵌套循环中没有任何影响?

有没有办法改善这段代码的内存管理?