python - 通过使用多线程/内核提高性能

标签 python performance python-multithreading

我有一个游戏(使用 pygame),我想提高它的性能。我注意到当我的 fps 很低时游戏最多只使用 20% 的 CPU,有没有办法可以使用线程来利用更多的 CPU?

我已经尝试实现线程,但似乎运气不佳,希望能提供一些帮助。

这个函数是导致延迟的原因:

第一版

def SearchFood(self):
    if not self.moving:
        tempArr = np.array([])

        for e in entityArr:
            if type(e) == Food:
                if e.rect != None and self.viewingRect != None:
                    if self.viewingRect.colliderect(e.rect):
                        tempArr = np.append(tempArr, e)

        if tempArr.size > 0:
            self.nearestFood = sorted(tempArr, key=lambda e: Mag((self.x - e.x, self.y - e.y)))[0]

第二个版本(较慢)

def SearchFood(self):
    if not self.moving:
        s_arr = sorted(entityArr, key=lambda e: math.hypot(self.x - e.x, self.y - e.y))

        for e, i in enumerate(s_arr):
            if type(e) != Food:
                self.nearestFood = None

            else:
                self.nearestFood = s_arr[i]
                break

我查看了整个实体列表,如果该实体是食物以及与想要吃所述食物的东西的距离,则对其进行排序。问题是实体数组有 500 个元素(或更多)长,因此需要很长时间来遍历和排序。然后补救我想通过使用线程来利用更多的 CPU。

如果有帮助,这里是完整的脚本:https://github.com/Lobsternator/Game-Of-Life-Esque.git

最佳答案

在 Python 中,线程不会增加使用的核心数。您必须改用多处理。
文档:https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing.Manager

关于python - 通过使用多线程/内核提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613660/

相关文章:

ios - 绘制背景颜色和边框和背景 PNG

python Pandas : select 2nd smallest value in groupby

python - 为什么在 Python 中计算点距离这么慢?

python - 在同时安装了 python 2.7 和 3.5 的 Windows 上使用 pip

php - 为什么 PHP 函数 imap_search() 很慢?

python 3.4 多处理

python - 如何处理两个事件循环? Pyrogram 和 Tkinter 的

python - 异步使用 Flask-Mail 导致 "RuntimeError: working outside of application context"

python - Pandas groupby : fill missing values from other group members

python - 使用 MatPlotLib 绘制点周围误差范围的折线图