Cython中穷举搜索的并行化

2024-04-27 03:26:20 发布

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

我对Cython还比较陌生,我正在尝试将我的一些代码Cythonize。我有一个复杂值的三维数组X(我把它当作一个大的正方形数组的“堆栈”),它的形状是(small, small, huge),我需要找到对角线上方最大项的位置和绝对值。我现在有这样一个详尽的搜索:

cdef double complex[:,:,:] Xcp = X.copy()

cdef Py_ssize_t h = Xcp.shape[0]
cdef Py_ssize_t w = Xcp.shape[1]
cdef Py_ssize_t l = Xcp.shape[2]
cdef Py_ssize_t j, k, m

cdef double tmptop = 0.0
cdef Py_ssize_t[:] coords = np.zeros((3), dtype="intp")
cdef double it

for j in range(l):
    for k in range(w):
        for m in range(k+1, h):
            it = cabs(Xcp[m, k, j])
            if it > tmptop:
                tmptop = it
                coords[0] = m
                coords[1] = k
                coords[2] = j 

注意,我从这里得到cabs

cdef extern from "complex.h":
    double cabs(double complex)

这个代码已经比我以前在Numpy中的代码快了很多,但是我确实觉得它可以被加速,特别是并行化。你知道吗

我尝试将循环更改为:

with nogil:
    for j in prange(l):
        for k in range(w):
            for m in range(k+1, h):
                it = abs(Xcp[m, k, j])
                if it > tmptop:
                    tmptop = it
                    coords[0] = m
                    coords[1] = k
                    coords[2] = j

尽管我现在得到了错误的结果。这是怎么回事?你知道吗


Tags: 代码inpyforrangeitcoordsdouble