假设我只有一个函数 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')
例如,如果我运行 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 来完成此任务。
最佳答案
您可以使用 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)
关于python - 在python中为多个参数并行运行单个函数的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63841162/