我想遍歷不同尺寸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