我正在使用PyQtGraph用于快速可视化我的数据采集。为此,我使用while
循环不断重绘数据。以下是该代码的简化版本:
import time
import numpy
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000)
y = numpy.cos(x)
# Plot
win = pg.GraphicsWindow()
win.resize(800, 800)
p = win.addPlot()
p.plot(x, y, pen = "y")
i = 0
while i < 5000:
start_time = time.time()
noise = numpy.random.normal(0, 1, len(y))
y_new = y + noise
p.plot(x, y_new, pen = "y", clear = True)
p.enableAutoRange("xy", False)
pg.QtGui.QApplication.processEvents()
i += 1
end_time = time.time()
print("It has been {0} seconds since the loop started".format(end_time - start_time))
win.close()
当我计时每次迭代时,发现我没有正确地清除图形。迭代时间不断增加,导致数据采集速度变慢。对于上面的示例,开始时迭代时间约为
0.009秒
,而结束时约为0.04秒
。因此,我有一个内存泄漏问题。我知道在
matplotlib
中,我应该调用clf()
来正确清除绘图。不幸的是,我并不熟悉PyQtGraph,并认为clear = True
会解决这个问题。我相信这是可能的,因为PyQtGraph
是为这种类型的使用而设计的。为了确保不减慢数据采集速度,我应该如何在每次迭代时清除图形?