如何使螺纹动画更快?

时间:2019-09-05 15:08:04

标签: python python-3.x matplotlib

我正在尝试每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()

1 个答案:

答案 0 :(得分:1)

由于Python的GIL(全局解释器锁),此处实际上没有并行发生任何事情。如果您想要真正的并发,则必须放弃threading来支持multiprocessing