如何使线程动画更快?



我正在尝试每 100 毫秒绘制一个直方图。

直方图的数据由线程并行生成并存储在全局变量中

对于直方图,如果bins=255,则动画变慢

我需要一些方法来使其更快

这是我的代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
import time
import threading
mutex = threading.RLock()
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
y = 0

def animate(i):
global y
mutex.acquire()
data = y
mutex.release()
ax1.clear()
ax1.hist(data, bins=255)

def data_collect_worker(nsize):
global y
y2 = []
while True:
y2 = [random.randint(0, 255) for i in range(int(nsize))]
mutex.acquire()
y = y2
mutex.release()
time.sleep(0.01)

if __name__ == '__main__':
x = threading.Thread(target=data_collect_worker, args=(255,))
x.start()
time.sleep(1)
animate(1)
ani = animation.FuncAnimation(fig, animate, interval=10)
plt.show()

由于Python的GIL(全局解释器锁(,这里实际上没有并行发生任何事情。如果你想要真正的并发性,你将不得不放弃threading,转而支持multiprocessing

最新更新