在 Python 中实现并行 for 循环

the*_*ron 10 python parallel-processing python-2.7 python-3.x

我有一个 Python 程序,它看起来像这样:

total_error = []
for i in range(24):
    error = some_function_call(parameters1, parameters2)
    total_error += error
Run Code Online (Sandbox Code Playgroud)

函数 'some_function_call' 需要很多时间,我找不到一种简单的方法来降低函数的时间复杂度。有没有办法在执行并行任务时仍然减少执行时间,然后将它们添加到 total_error 中。我尝试使用 pool 和 joblib 但都无法成功使用。

Ger*_*ges 16

您也可以concurrent.futures在 Python 3 中使用,这是一个比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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,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)
Run Code Online (Sandbox Code Playgroud)


Net*_*ave 6

您可以使用 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)
Run Code Online (Sandbox Code Playgroud)