我一直在使用matplotlib动画函数来显示一些实时数据。运行几分钟后,我注意到python使用的内存不断爬起来。我决定回到一些动画的例子,看看他们在我的电脑上是否有同样的问题。matplotlib动画内存泄漏
当我使用animate_decay.py示例并将False重复为True时,我可以模拟我的实时数据程序所展示的相同问题。这是一个变化的代码。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(t=0):
cnt = 0
while cnt < 1000:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
del ydata[:]
line.set_data(xdata, ydata)
return line,
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []
def run(data):
# update the data
t, y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)
return line,
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
repeat=True, init_func=init, save_count=0)
plt.show()
我正在使用Mac(OS X 10.10),并通过活动监视器观看内存蟒蛇使用。随着动画一遍又一遍地重复播放,蟒蛇正在抓取越来越多的内存。几分钟后,蟒蛇使用超过300Mb。
此问题类似于以下问题:Memory usage for matplotlib animation但未回答。
我已经尝试在运行函数中插入垃圾收集,但这并没有帮助。我也用python 2.7和python 3.5尝试了matplotlib,结果相同。还有什么建议?预期这种行为?
我跑你的代码不变在Win10,Python 2.7版,蟒蛇64位的IPython的笔记本电脑,我看到使用87.1 MB的过程中,有小幅波动,但总是在第一回来了相同数量的一会儿。 10分钟后在87.6 MB。 – roadrunner66
奇怪。无论我如何运行代码,我都有内存问题。粘贴到python,ipython笔记本或命令行。我也使用anaconda 4.0。也许这与默认图形有关? –
Win7,Anaconda 3.11.0-dirty,Ipthon Notebook 2.7与Qt4Agg后端在15分钟左右从68.8MB变为69.5MB。无法重现该问题。 – ljetibo