Python 如何使线程动画更快?

Python 如何使线程动画更快?,python,python-3.x,matplotlib,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

我试图每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(全局解释器锁)的原因,这里实际上没有并行发生任何事情。如果您想要真正的并发性,您将不得不放弃
线程化
,转而采用
多处理
FuncAnimation(…,interval=10)
“我正在尝试每100ms绘制一个直方图。”。你也在睡觉,我不确定这是否只是一个占位符,为其他需要时间的东西。你看到了吗,这是一个60帧的运行速度,我有300个箱子。它的结构非常不同,这表明它对您来说很慢的原因是因为您错误地使用了它。非常确定,这与Python的GIL无关!为什么会这样说?@SamMason“直方图的数据是由并行线程生成的”“我需要一些方法使它更快”因为它实际上不是并行的,我在这里没有看到任何IO绑定操作,使用
线程化
会降低性能,而使用
多处理
将大大加快速度。