[英]Implement Parallel for loops in Python
我有一个 Python 程序,它看起来像这样:
total_error = []
for i in range(24):
error = some_function_call(parameters1, parameters2)
total_error += error
函数 'some_function_call' 需要很多时间,我找不到一种简单的方法来降低函数的时间复杂度。 有没有办法在执行并行任务时仍然减少执行时间,然后将它们添加到 total_error 中。 我尝试使用 pool 和 joblib 但都无法成功使用。
您还可以在 Python 3 中使用concurrent.futures
,这是一个比multiprocessing
更简单的接口。 有关差异的更多详细信息, 请参见此处。
from concurrent import futures
total_error = 0
with futures.ProcessPoolExecutor() as pool:
for error in pool.map(some_function_call, parameters1, parameters2):
total_error += error
在这种情况下, parameters1
和parameters2
应该是一个列表或大小与您想要运行该函数的次数相同的可迭代对象(根据您的示例为 24 次)。
如果paramters<1,2>
不是可迭代/可映射的,但您只想运行该函数 24 次,您可以为该函数提交所需次数的作业,然后使用回调获取结果。
class TotalError:
def __init__(self):
self.value = 0
def __call__(self, r):
self.value += r.result()
total_error = TotalError()
with futures.ProcessPoolExecutor() as pool:
for i in range(24):
future_result = pool.submit(some_function_call, parameters1, parameters2)
future_result.add_done_callback(total_error)
print(total_error.value)
您可以使用 python multiprocessing
:
from multiprocessing import Pool, freeze_support, cpu_count
import os
all_args = [(parameters1, parameters2) for i in range(24)]
# call freeze_support() if in Windows
if os.name == "nt":
freeze_support()
# you can use whatever, but your machine core count is usually a good choice (although maybe not the best)
pool = Pool(cpu_count())
def wrapped_some_function_call(args):
"""
we need to wrap the call to unpack the parameters
we build before as a tuple for being able to use pool.map
"""
sume_function_call(*args)
results = pool.map(wrapped_some_function_call, all_args)
total_error = sum(results)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.