Cython和numpy如何摆脱花哨的索引(不调用Python)

2024-04-27 00:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个三维纽比阵列的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]时,我想这是因为它推断了另外两个维度的大小,但即使在第二和第三个轴使用类型化范围时,这一行仍然是黄色的!在

^{pr2}$

Tags: infornponesrangearrayperformint
1条回答
网友
1楼 · 发布于 2024-04-27 00:12:25

与将内容声明为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进行索引。在

相关问题 更多 >