我有一个运行循环的 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)

输出是:
=== before: 71598.08
=== after: 170237.952
=== before: 170237.952
=== after: 255696.896
=== before: 255696.896
=== after: 341409.792

如您所见,在调用之前程序有内存占用,在调用之后它增加,但在下一次调用之前保持稳定。

为什么是这样?由于 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')

并使用以下内容将 10 个数字绘制到磁盘上:
plot_line(index,alt,'-','Drive Index','Altitude in m',output_dir + 'name.png')

如果我评论使用 plot_line 的行,问题就不会发生,所以泄漏应该在这行代码上。

谢谢

最佳答案

问题依赖于创建和从未关闭的如此多的数字。不知何故,python 让他们都活着。

我添加了该行

plt.close()

对于我的每个绘图函数 plot_lineplot_hist,问题就消失了。

关于python循环迅速增加其内存使用量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16080979/

10-09 05:44
查看更多