我有一个数据分析模块,其中包含调用的函数matplotlib.pyplot
API 多次,每次运行最多生成 30 个数字。这些数字在生成后会立即写入磁盘,因此我需要将它们从内存中清除。
目前,在每个函数结束时,我都会:
import matplotlib.pyplot as plt
plt.clf()
不过,我不太确定这个语句是否真的可以清除内存。我特别担心,因为我发现每次运行模块进行调试时,我的可用内存空间都会不断减少。
每次将绘图写入磁盘后,我需要做什么才能真正清除内存?
经过一周的试验,我得到了我的解决方案!希望它可以帮助你。
我的演示已附上。
import matplotlib.pyplot as plt
import numpy as np
A = np.arange(1,5)
B = A**2
cnt=0
while(1):
cnt = cnt+1
print("########### test %d ###########" % cnt)
# here is the trick:
# set the figure a 'num' to prevent from re-malloc of a figure in the next loop
# and set "clear=True" to make the figure clear
# I never use plt.close() to kill the figure, because I found it doesn't work.
# Only one figure is allocated, which can be self-released when the program quits.
# Before: 6000 times calling of plt.figure() ~ about 1.6GB of memory leak
# Now: the memory keeps in a stable level
fig = plt.figure(num=1, clear=True)
ax = fig.add_subplot()
# alternatively use an other function in one line
# fig, ax = plt.subplots(num=1,clear=True)
ax.plot(A,B)
ax.plot(B,A)
# Here add the functions you need
# plt.show()
fig.savefig('%d.png' % cnt)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)