Aluode/PerceptionLabPortable
0
1from time import perf_counter2 3import numpy as np4 5import pyqtgraph as pg6 7app = pg.mkQApp()8plt = pg.PlotWidget()9 10app.processEvents()11 12## Putting this at the beginning or end does not have much effect13plt.show() 14 15## The auto-range is recomputed after each item is added,16## so disabling it before plotting helps17plt.enableAutoRange(False, False)18 19def plot():20 start = perf_counter()21 n = 1522 pts = 10023 x = np.linspace(0, 0.8, pts)24 y = np.random.random(size=pts)*0.825 for i in range(n):26 for j in range(n):27 ## calling PlotWidget.plot() generates a PlotDataItem, which 28 ## has a bit more overhead than PlotCurveItem, which is all 29 ## we need here. This overhead adds up quickly and makes a big30 ## difference in speed.31 32 plt.addItem(pg.PlotCurveItem(x=x+i, y=y+j))33 34 dt = perf_counter() - start35 print(f"Create plots took: {dt * 1000:.3f} ms")36 37## Plot and clear 5 times, printing the time it took38for _ in range(5):39 plt.clear()40 plot()41 app.processEvents()42 plt.autoRange()43 44 45 46 47 48def fastPlot():49 ## Different approach: generate a single item with all data points.50 ## This runs many times faster.51 start = perf_counter()52 n = 1553 pts = 10054 x = np.linspace(0, 0.8, pts)55 y = np.random.random(size=pts)*0.856 shape = (n, n, pts)57 xdata = np.empty(shape)58 xdata[:] = x + np.arange(shape[1]).reshape((1,-1,1))59 ydata = np.empty(shape)60 ydata[:] = y + np.arange(shape[0]).reshape((-1,1,1))61 conn = np.ones(shape, dtype=bool)62 conn[...,-1] = False # make sure plots are disconnected63 item = pg.PlotCurveItem()64 item.setData(xdata.ravel(), ydata.ravel(), connect=conn.ravel())65 plt.addItem(item)66 67 dt = perf_counter() - start68 print("Create plots took: %0.3fms" % (dt*1000))69 70 71## Plot and clear 5 times, printing the time it took72for _ in range(5):73 plt.clear()74 fastPlot()75 app.processEvents()76 plt.autoRange()77 78if __name__ == '__main__':79 pg.exec()80 