我想遍历不同尺寸numpy的阵列的列表,然后将其传入到不需要用Cython功能GIL:用Cython迭代numpy的数组列表不吉
# a has T1 rows and M columns
a = np.array([[0.0, 0.1, 0.3, 0.7],
[0.1, 0.2, 0.1, 0.6],
[0.1, 0.2, 0.1, 0.6]])
# b has T2 rows and M columns
b = np.array([[1.0, 0.0, 0.0, 0.0],
[0.1, 0.2, 0.1, 0.6]])
# c has T3 rows and M columns
c = np.array([[0.1, 0.0, 0.3, 0.6],
[0.5, 0.2, 0.3, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.1, 0.0]])
array_list = [a, b, c]
N = len(array_list)
# this function works
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void function_not_requiring_the_gil(double[:, ::1] arr) nogil:
cdef int T = arr.shape[0]
cdef int M = arr.shape[1]
cdef int i, t
for t in range(T):
for i in range(M):
# do some arbitrary thing to the array in-place
arr[t, i] += 0.001
# issue is with this function
def function_with_loop_over_arrays(array_list, int N):
cdef int i
with nogil:
for i in range(N):
function_not_requiring_the_gil(array_list[i])
当我编译用Cython代码,我得到以下错误:
Error compiling Cython file:
------------------------------------------------------------
...
def function_with_loop_over_arrays(array_list, int N):
cdef int i
with nogil:
for i in range(N):
function_not_requiring_the_gil(array_list[i]) ^
------------------------------------------------------------
my_file.pyx:312:53: Indexing Python object not allowed without gil
有另一种类型的数据结构,我可以代替使用Python列表来存储这些numpy的阵列,这样我就可以在它们之间迭代,而不吉尔?我打开涉及malloc C指针/ Cython memoryviews /其他类型,我不知道的建议。
请注意,每个numpy数组的行数不同,但数组列表的长度是已知的。
感谢downvote! –
@ B.M。好吧,我添加了一条评论,解释为什么我低估了你的答案。有什么问题吗? –
非常感谢您的回答,它确实解决了我的问题,但需要修改nogil函数以采用不同的参数。我实际上有几个我想在这个循环中调用的nogil函数,并且它们中的每一个都以多个数组作为输入,所以不得不为每个原始数组传递两个参数(开始指针和行数)这些函数的参数数量。有没有什么办法可以让我自己传递数组/记忆体视图?如果不是,我会接受你的答案。 – user3570195