gpt4 book ai didi

python - 如何加快python函数中的 'for'循环?

转载 作者:行者123 更新时间:2023-12-03 19:05:16 25 4
gpt4 key购买 nike

我有一个函数var .我想知道通过利用系统拥有的所有处理器、内核和 RAM 内存的多处理/并行处理,在此函数中快速运行 for 循环(对于多个坐标:xs 和 ys)的最佳方法。
是否可以使用 Dask模块?pysheds可以找到文档 here .

import numpy as np
from pysheds.grid import Grid

xs = 82.1206, 72.4542, 65.0431, 83.8056, 35.6744
ys = 25.2111, 17.9458, 13.8844, 10.0833, 24.8306


for (x,y) in zip(xs,ys):

grid = Grid.from_raster('E:/data.tif', data_name='map')
grid.catchment(data='map', x=x, y=y, out_name='catch', recursionlimit=1500, xytype='label')
....
....
results

最佳答案

我试图在下面使用 dask 给出一个可重现的代码.可以添加pysheds的主处理部分或其中的任何其他函数,以更快地并行迭代参数。dask 的文档模块可以找到here .

import dask
from dask import delayed, compute
from dask.distributed import Client, progress
from pysheds.grid import Grid

client = Client(threads_per_worker=2, n_workers=2) #Choose the number of workers and threads per worker over here to deploy for your task.

xs = 82.1206, 72.4542, 65.0431, 83.8056, 35.6744
ys = 25.2111, 17.9458, 13.8844, 10.0833, 24.8306

#Firstly, a function has to be created, where the iteration of the parameters is involved.
def var(x,y):

grid = Grid.from_raster('data.tif', data_name='map')
grid.catchment(data='map', x=x, y=y, out_name='catch', recursionlimit=1500, xytype='label')
...
...
return (result)

#Now calling the function in a 'dask' way.
lazy_results = []

for (x,y) in zip(xs,ys):
lazy_result = dask.delayed(var)(x,y)
lazy_results.append(lazy_result)

#Final command to execute the function var(x,y) and get the result.
dask.compute(*lazy_results)

关于python - 如何加快python函数中的 'for'循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63804346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com