jea*_*ean 3 python numpy cython
我想在 3 维 numpy 数组的 for 循环中释放 GIL
cdef np.ndarray[DTYPE_t,ndim=3] array=np.ones((10000000,4,2))
cdef np.ndarray[DTYPE_t,ndim=2] sliced_array
cdef int i
cdef int N=array.shape[0]
for i in range(N):
sliced_array=array[i]
#perform computations on slice
Run Code Online (Sandbox Code Playgroud)
当我查看 Cython 生成的 html 时,它看起来像是在调用 Python,sliced_array=array[i]我猜这是因为它推断了其他两个维度的大小,但即使在第二个和第三个轴使用类型化范围时,这条线仍然是黄色 !
sliced_array=array[i,typed_slice_x,typed_slice_y]
Run Code Online (Sandbox Code Playgroud)
与将事物声明为 numpy 数组相比,较新的 memoryview 语法的优点之一是您可以在没有 GIL 的情况下进行索引操作:
cdef double[:,:,:] array=np.ones((10000000,4,2))
cdef double[:,:] sliced_array
cdef int i
cdef int N=array.shape[0]
for i in range(N):
with nogil: # just to prove the point
sliced_array=array[i,:,:]
Run Code Online (Sandbox Code Playgroud)
如果你将它们声明为cdef np.ndarray那么你就不能轻易避免需要 GIL 进行索引。
| 归档时间: |
|
| 查看次数: |
390 次 |
| 最近记录: |