python循环迅速增加其内存使用量

otm*_*ger 3 python profiler memory-leaks

我有一个运行循环的python脚本.在这个循环中,DoDebugInfo每个循环迭代调用一次该函数.此功能基本上使用matplotlib将一些图片打印到硬盘,导出KML文件并进行其他一些计算,并且不返回任何内容.

我遇到了python的问题,对于每次运行,该函数都会DoDebugInfo占用越来越多的RAM.我猜一些变量正在增加每个循环的大小.

我在通话前后添加了以下几行:

print '=== before: ' + str(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000)
DoDebugInfo(inputs)
print '=== after: ' + str(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000)
Run Code Online (Sandbox Code Playgroud)

输出是:

=== before: 71598.08
=== after: 170237.952
=== before: 170237.952
=== after: 255696.896
=== before: 255696.896
=== after: 341409.792
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在调用之前程序具有内存占用,并且在调用之后它会增加,但在下一次调用之前保持稳定.

为什么是这样?因为DoDebugInfo(inputs)是一个什么都不返回的函数,一些变量如何留在内存中呢?是否需要清除函数末尾的所有变量?

编辑:DoDebugInfo导入此功能:

def plot_line(x,y,kind,lab_x,lab_y,filename):
    fig = plt.figure(figsize=(11,6),dpi=300)
    ax = fig.add_subplot(111)
    ax.grid(True,which='both')
    #print 'plotting'
    if type(x[0]) is datetime.datetime:
        #print 'datetime detected'
        ax.plot_date(matplotlib.dates.date2num(x),y,kind)
        ax.fmt_xdata = DateFormatter('%H')
        ax.autoscale_view()
        fig.autofmt_xdate()
    else:   
        #print 'no datetime'
        ax.plot(x,y,kind)
    xlabel = ax.set_xlabel(lab_x)
    ax.set_ylabel(lab_y)
    fig.savefig(filename,bbox_extra_artists=[xlabel], bbox_inches='tight')

def plot_hist(x,Nbins,lab_x,lab_y,filename):
    fig = plt.figure(figsize=(11,6),dpi=300)
    ax = fig.add_subplot(111)
    ax.grid(True,which='both')
    ax.hist(x,Nbins)
    xlabel = ax.set_xlabel(lab_x)
    ax.set_ylabel(lab_y)
    fig.savefig(filename,bbox_extra_artists=[xlabel], bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)

并使用以下内容将10个数字绘制到磁盘上:

plot_line(index,alt,'-','Drive Index','Altitude in m',output_dir + 'name.png')
Run Code Online (Sandbox Code Playgroud)

如果我评论使用plot_line该问题的行不会发生,那么泄漏应该在这行代码上.

谢谢

otm*_*ger 5

这个问题依赖于创建和永不关闭的数字.不知何故python让他们都活着.

我添加了这条线

plt.close()
Run Code Online (Sandbox Code Playgroud)

对我的每个情节功能plot_line而且plot_hist问题都消失了.