在python中为多个参数并行运行单个函数的最快方法

mAr*_*Ark 5 python parallel-processing function multiprocessing embarrassingly-parallel

假设我只有一个函数processing。我想为多个参数并行运行相同的函数多次,而不是一个接一个地依次运行。

def processing(image_location):
    
    image = rasterio.open(image_location)
    ...
    ...
    return(result)

#calling function serially one after the other with different parameters and saving the results to a variable.
results1 = processing(r'/home/test/image_1.tif')
results2 = processing(r'/home/test/image_2.tif')
results3 = processing(r'/home/test/image_3.tif')

Run Code Online (Sandbox Code Playgroud)

例如,如果我运行delineation(r'/home/test/image_1.tif')然后delineation(r'/home/test/image_2.tif'),然后delineation(r'/home/test/image_3.tif'),如图上面的代码,这将顺序运行一前一后,并且如果需要5分钟一个函数来运行然后运行这三个将采取5X3 = 15分钟。因此,我想知道我是否可以并行/尴尬地并行运行这三个,以便对所有三个不同参数执行该函数只需要 5 分钟。

帮助我以最快的方式完成这项工作。该脚本应该能够利用默认情况下可用的所有资源/CPU/ram 来完成此任务。

Ald*_*ven 3

您可以使用multiprocessing并行执行函数并将结果保存到results变量:

from multiprocessing.pool import ThreadPool

pool = ThreadPool()
images = [r'/home/test/image_1.tif', r'/home/test/image_2.tif', r'/home/test/image_3.tif']
results = pool.map(delineation, images)
Run Code Online (Sandbox Code Playgroud)