Cython with numpy 如何摆脱花哨的索引(没有调用 Python)



我想在三维 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

当我查看 Cython 生成的 html 时,它看起来像是在调用 Python,因为它正在执行sliced_array=array[i]我想这是因为它推断了其他两个维度的大小,但即使对第二和第三轴使用类型化范围,这条线仍然是黄色的!

sliced_array=array[i,typed_slice_x,typed_slice_y]

与将事物声明为 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,:,:]

如果将它们声明为cdef np.ndarray则无法轻松避免需要 GIL 进行索引。

最新更新