Python Matplotlib:指定图形大小时未释放内存 [英] Python matplotlib: memory not being released when specifying figure size

查看:155
本文介绍了Python Matplotlib:指定图形大小时未释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib生成许多数值模拟结果图.这些图用作视频中的帧,因此我通过重复调用与此函数类似的函数来生成许多图:

I'm using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I'm generating many of them by repeatedly calling a function similar to this one:

from pylab import *

def plot_density(filename,i,t,psi_Na):  
    figure(figsize=(8,6))
    imshow(abs(psi_Na)**2,origin = 'lower')
    savefig(filename + '_%04d.png'%i)
    clf()

问题在于,每次调用此函数时,python进程的内存使用量都会增加几兆字节.例如,如果我通过以下循环调用它:

The problem is that the memory usage of the python process grows by a couple of megabytes with every call to this function. For example if I call it with this loop:

if __name__ == "__main__":
    x = linspace(-6e-6,6e-6,128,endpoint=False)
    y = linspace(-6e-6,6e-6,128,endpoint=False)
    X,Y = meshgrid(x,y)
    k = 1000000
    omega = 200
    times = linspace(0,100e-3,100,endpoint=False)
    for i,t in enumerate(times):
        psi_Na = sin(k*X-omega*t)
        plot_density('wavefunction',i,t,psi_Na)
        print i

然后,ram使用量会随着时间增长到600MB.但是,如果我在函数定义中注释了figure(figsize=(8,6))行,则ram的使用保持稳定在52MB. (8,6)是默认图形尺寸,因此在两种情况下都会产生相同的图像.我想根据我的数值数据制作不同大小的图,而不会用完内存.我如何强制python释放此内存?

then the ram usage grows with time to 600MB. If however I comment out the line figure(figsize=(8,6)) in the function definition, then the ram usage stays steady at 52MB. (8,6) is the default figure size and so identical images are produced in both cases. I'd like to make different sized plots from my numerical data without running out of ram. How might I force python to free up this memory?

我已经尝试过gc.collect()每个循环来强制进行垃圾收集,并且我已经尝试过f = gcf()获取当前图形,然后尝试del f删除它,但无济于事.

I've tried gc.collect() each loop to force garbage collection, and I've tried f = gcf() to get the current figure and then del f to delete it, but to no avail.

我正在64位Ubuntu 10.04上运行CPython 2.6.5.

I'm running CPython 2.6.5 on 64 bit Ubuntu 10.04.

推荐答案

来自pylab.figure的文档字符串:

In [313]: pylab.figure?

如果要创建许多图形,请 确保您明确调用关闭" 您没有使用的数字,因为 这将使pylab能够正确运行 清理内存.

If you are creating many figures, make sure you explicitly call "close" on the figures you are not using, because this will enable pylab to properly clean up the memory.

所以也许尝试:

pylab.close()     # closes the current figure

这篇关于Python Matplotlib:指定图形大小时未释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆