1
我正在使用matplotlib來運行實時船模擬器。下面的代碼是一個非常短的代碼來說明我使用matplotlib創建動畫圖的方法。代碼在特定座標上繪製一個簡單的船並旋轉它。動畫Python Matplotlib圖中的更新速度較慢。我如何讓它更快?
我應該使用什麼方法,如果我想這個繪圖渲染速度比14fps更快?例如,在matplotlib中有沒有獲取GPU渲染的方法?運行該腳本
import time
import math
from matplotlib import pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Polygon
# boat dimensions
l = 10.0 #m
w = 3.0 #m
b = 2.0 #m
fig = plt.figure(figsize=(3,3))
subplot_def = 111
ax = fig.add_subplot(subplot_def)
plt.ion() # set plot to animated
fig.canvas.draw()
plt.show(block=False)
prev_time = time.time() # for getting fps
simulation_start_time = time.time() # how long the simulation has been running
while True:
time_debug = time.time()
current_time = time.time() - simulation_start_time
# set boat coordinates
boat_x = 100*math.sin(current_time/100.0)
boat_y = 10*math.sin(current_time/100.0)
boat_z = current_time/2*math.pi
# rotate the boat
ts = ax.transData
tr = mpl.transforms.Affine2D().rotate_around(boat_x, boat_y, boat_z)
t = tr + ts
print("transform: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
time_debug = time.time()
# clear the previous plot
ax.clear()
print("clear: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
time_debug = time.time()
# add boat
boat1 = Polygon(
[[-w/2.0 + boat_x, -l/2.0 + boat_y], [0 + boat_x, l/2.0 + boat_y], [w/2.0 + boat_x, -l/2.0 + boat_y]],
closed=True, color='lightsteelblue', transform=t
)
ax.add_artist(boat1)
# set plot limits
ax.set_xlim([boat_x - 10, boat_x + 10])
ax.set_ylim([boat_y - 10, boat_y + 10])
# update plot
fig.canvas.update()
print("draw plot: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
time_debug = time.time()
print('total plot update rate: {:.3f} ms or {:.1f} fps'.format((time.time()-prev_time)*1000, 1/(time.time()-prev_time)))
prev_time = time.time()
plt.pause(0.001)
輸出:
transform: 0.000 ms, clear: 25.002 ms, draw plot: 0.000 ms, total plot update rate: 67.007 ms or 14.9 fps
transform: 0.000 ms, clear: 31.003 ms, draw plot: 1.000 ms, total plot update rate: 76.008 ms or 13.2 fps
transform: 0.000 ms, clear: 26.002 ms, draw plot: 1.000 ms, total plot update rate: 73.007 ms or 13.7 fps
我嘗試過了,它是有點什麼,我去爲方向。但是,從以前的設置中不可以使用GPU加速和line.set_ydata來獲得更快的性能。問題是,對於我的情況,我相信我需要清除每次迭代的數字。謝謝你。 – sebnil