gpt4 book ai didi

Python matplotlib : memory not being released when specifying figure size

转载 作者:IT老高 更新时间:2023-10-28 22:21:22 26 4
gpt4 key购买 nike

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

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 进程的内存使用量都会增加几兆字节。例如,如果我用这个循环调用它:

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

然后内存使用量随时间增长到 600MB。但是,如果我在函数定义中注释掉 figure(figsize=(8,6)) 行,那么 ram 使用量将稳定在 52MB。 (8,6) 是默认图形大小,因此在两种情况下都会生成相同的图像。我想从我的数值数据中制作不同大小的图,而不会用完 ram。我如何强制 python 释放这个内存?

我试过 gc.collect() 每个循环来强制垃圾收集,我试过 f = gcf() 来获取当前的数字,然后del f 将其删除,但无济于事。

我在 64 位 Ubuntu 10.04 上运行 CPython 2.6.5。

最佳答案

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

In [313]: pylab.figure?

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 : memory not being released when specifying figure size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com