python到cython消除python调用

2024-09-28 19:10:04 发布

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

我正在尝试将以下循环转换为cython:

cimport numpy as np
cimport cython
@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(cells, int nmbcellsx):
    cdef np.ndarray[float, ndim=1] x,y,z
    cdef int i,j,len
    for i in range(nmbcellsx):
      x = cells[i].x
      y = cells[i].y
      z = cells[i].z
      len = x.size
      for j in range(len):
         x[j] = x[j] * y[j] * z[j]

    return 0

到目前为止,一切看起来还不错,但是访问cells[i].*仍然需要python调用。这会阻止i循环的并行化。在

下面是一个cython反馈(由cython-a生成):

cython -a feedback

因此,问题是:如何删除这些python回调(即,使第9-12行变为白色)?在

当我尝试像这样添加单元格类型时:

^{pr2}$

我收到以下cython错误:dtype必须是“object”、数值类型或结构(它正在抱怨声明中的单元格)

非常感谢。在


Tags: innumpy类型forlenasnprange
2条回答

Typed Memoryview怎么样?在

cimport cython

cdef class cell_t:
    cdef public float[:] x, y, z

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(cell_t[:] cells, int nmbcellsx):
    cdef float[:] x,y,z
    cdef int i,j,length
    cdef cell_t cell
    for i in range(nmbcellsx):
        cell = cells[i]
        x = cell.x
        y = cell.y
        z = cell.z
        length = len(x)
        for j in range(length):
            x[j] = x[j] * y[j] * z[j]
    return 0

测试代码如下:

^{pr2}$

以及输出:

[  28.   80.  162.]
[ 6.  6.  6.  6.  6.]

您没有告诉Cython您的cells参数的类型,因此它将使用Python查找方法。尝试将定义更改为以下内容:

def Interpolation(np.ndarray cells, int nmbcellsx):

这将告诉Cython它正在获取ndarray类型,因此可以使用C访问。在

相关问题 更多 >