假设我有一个函数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来完成此任务
你可能想看看IPython Parallel。它允许您在负载平衡(本地)集群上轻松运行函数
对于这个小示例,请确保已安装IPython Parallel、NumPy和Pillow。要运行示例,首先需要启动集群。要启动具有四个并行引擎的本地集群,请在终端中键入(一个引擎对应一个处理器核心似乎是一个合理的选择):
然后,您可以运行以下脚本,该脚本在给定目录中搜索jpg图像,并计算每个图像中的像素数:
您可以使用
multiprocessing
并行执行函数,并将结果保存到results
变量:使用
multiprocessing
库的另一种写入方式(请参阅@Alderven以了解其他函数)results
变量将包含一个包含已处理数据的列表。然后你就可以写了相关问题 更多 >
编程相关推荐