gpt4 book ai didi

python - 并行运行多个函数,并将所有结果收集在一个列表中

转载 作者:太空狗 更新时间:2023-10-30 02:13:16 26 4
gpt4 key购买 nike

我有一个非常占用 CPU 的函数:

def entity_intersections(ent, collidable):
intersections = []

for line1, line2 in product(ent.shape, collidable.shape):

pair_intersections = find_intersections(line1 + ent.position, ent.velocity, ent.acceleration, line2 + collidable.position, collidable.velocity, collidable.acceleration, ent, collidable)
intersections.extend(pair_intersections)

return intersections

我想让所有对 find_intersections 的调用并行运行,以便它们执行得更快,同时仍将所有结果收集在一起(一旦所有执行完成)。考虑到 find_intersectionspure function,哪个库允许我这样做?

我们将不胜感激如何生成这些并行执行以及如何收集结果的示例。

最佳答案

最简单的方法是使用multiprocessing模块:

class FindIntersectionsWrapper(object):
def __init__(self, ent, collidable):
self.ent = ent
self.collidable = collidable
def __call__(self, dims):
line1, line2 = dims
return find_intersections(
line1 + self.ent.position, self.ent.velocity,
self.ent.acceleration, line2 + self.collidable.position,
self.collidable.velocity, self.collidable.acceleration,
self.ent, self.collidable)

def entity_intersections(ent, collidable):
find_inter = FindIntersectionsWrapper(ent, collidable)
pool = multiprocessing.Pool()
return pool.map(find_inter, product(ent.shape, collidable.shape))

辅助函数 find_intersections_wrapper() 是必需的,因为 Pool.map() 需要一个带有单个参数的函数。

您可能希望将 pool 的创建移出 entity_intersections() 以减少仅生成一次进程池的开销。

编辑:使用类而不是闭包,因为传递给 Pool.map() 的可调用对象在 Windows 上必须是可挑选的。

关于python - 并行运行多个函数,并将所有结果收集在一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com