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

标签 python function parallel-processing 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')

例如,如果我运行 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/

相关文章:

python - 替换 pandas 多索引数据框中的值

python - 如果所有值都等于字符串值,则删除列

c++ - 是否有 tbb::parallel_for 的中断命令

c# - 并行发送批量电子邮件的最佳方式

python - 语法无效: function doesn't return value [closed]

c++ - 在 __host__ __device__ 仿函数中创建 Thrust::device_vectors

python - Dialogflow - 通过 v2 API 创建带有输入上下文的 Intent

python - 如何在pytorch中求偏导数

c - 将数组值传递给另一个函数时出现缓冲区溢出问题

python - 如何在字符串中打印函数?