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

标签 python memory-leaks profiler

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

相关文章:

python - 如何使用 networkx + python 枚举图中所有*最大*派系?

python - BioPython:如何将氨基酸字母表转换为

c++ - C/C++ 内存泄漏(使用 PCRE)

java - 在 Junit 中使用 Java 分析器

asp.net - 报告计算时间下的 Visual Studio 诊断工具

Symfony 4 在 Controller 操作中禁用分析器

python - 使用 python 每页多个 png/pdf

python - 类型错误 : Unsupported type <class 'numpy.dtype' > in write()

.net-3.5 - .Net 3.5 中 BinaryFormatter 类的内存泄漏问题

python - 在 Mac OS 终端中运行 python 时内存泄漏