gpt4 book ai didi

python 到 cython - 消除 python 调用

转载 作者:行者123 更新时间:2023-11-28 22:58:02 24 4
gpt4 key购买 nike

我目前正在尝试将以下循环转换为 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-loop 的并行化。

这是一个 cython 反馈(用 cython -a 生成):

cython -a feedback

问题由此而来:如何删除这些 python 回调(即第 9-12 行变为白色)?

当我尝试像这样添加 Cell 的类型时:

cimport numpy as np
cimport cython

cdef class cell_t:
cdef np.ndarray x,y,z

@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(np.ndarray[cell_t,ndim=1] 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

我收到以下 cython 错误:dtype 必须是“对象”、数字类型或结构(它提示声明中的 cell_t)

非常感谢。

最佳答案

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

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

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

关于python 到 cython - 消除 python 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com