【发布时间】:2016-08-06 14:20:54
【问题描述】:
我一直在使用 matplotlib 动画函数来显示一些实时数据。运行了几分钟后,我注意到 python 使用的内存不断增加。我决定回到一些动画示例,看看它们在我的计算机上是否有同样的问题。
当我使用 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),并通过 Activity Monitor 观察 python 使用的内存。随着动画一遍又一遍地重复,python 正在抢占越来越多的内存。几分钟后,python 使用了超过 300Mb。
这个问题与Memory usage for matplotlib animation的问题类似,但没有得到回答。
我尝试在运行函数中插入垃圾回收,但这没有帮助。我还尝试了 matplotlib 与 python 2.7 和 python 3.5,结果相同。有什么进一步的建议吗?这是预期的行为吗?
【问题讨论】:
-
我在 Win10、Python 2.7、Anaconda 64 位的 Ipython 笔记本上运行您的代码,我看到该进程使用 87.1 MB,略有波动,但总是返回相同的数字在最初的几分钟内。 10 多分钟后达到 87.6 MB。
-
奇怪。无论我如何运行代码,我都有内存问题。粘贴到 python、ipython notebook 或命令行中。我也在使用 anaconda 4.0。也许这与默认图形有关?
-
Win7、Anaconda 3.11.0-dirty、带有 Qt4Agg 后端的 Ipython Notebook 2.7 在 15 分钟左右从 68.8MB 变为 69.5MB。无法重现该问题。
-
感谢 ljetibo 和 @roadrunner66 尝试重现此问题。 Mac 上的默认后端就是问题所在。我试过 Qt4Agg 和 TkAgg,都很好用!
标签: python animation matplotlib memory-leaks