GIL锁定是否会显着降低以下代码的性能?
每个块上的函数使用python循环而不是numpy函数。由于外部库,我必须使用python循环。
测试代码:
import numpy as np
import dask.array as da
import dask.sharedict as sharedict
from itertools import product
def block_func(block):
for i in range(len(block)): # <--- the python loop ...
block[i] += 1
return block
def darr_func(x, name='test'):
dsk = {}
for idx in product(*map(range, x.numblocks)):
dsk[(name,) + idx] = (block_func, (x.name,) + idx)
dsk2 = sharedict.merge((name, dsk), x.dask)
return da.Array(dsk2, name, x.chunks, x.dtype)
def main():
n = 1000
chunks = 100
arr = np.arange(n*n).reshape(n, n)
darr = da.from_array(arr, chunks=chunks)
result = darr_func(darr)
print(result.compute())
main()
如果是这种情况,可以为调度程序设置上下文帮助吗? 如何在dask数组上设置函数的上下文?我想在dask数组上使用默认的dask调度程序进行其他操作。
从wiki中,我看到了为计算而不是函数设置调度程序的方法:
# As a context manager
>>> with dask.set_options(get=dask.multiprocessing.get):
... x.sum().compute()
# Set globally
>>> dask.set_options(get=dask.multiprocessing.get)
>>> x.sum().compute()
答案 0 :(得分:1)
Python for循环不会释放GIL,因此难以与线程并行化。在这种情况下,您有几个选项
使用将计算拆分为多个进程的调度程序。我个人的建议是在本地使用dask.distributed调度程序,这可以通过运行以下两行来完成:
from dask.distributed import Client
client = Client()
然而,与往常一样,您应该分析您的代码并尝试一些事情。上面给出的建议取决于许多因素。例如,如果循环体释放GIL,则Python for循环可能不是问题。