我有一个游戏(使用 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/