【发布时间】:2018-07-10 15:15:32
【问题描述】:
我正在尝试创建一个简单的 cython 模块并遇到以下问题。我想创建一个类似的函数:
cdef float calc(float[:] a1, float[:] a2):
cdef float res = 0
cdef int l = len(a2)
cdef float item_a2
cdef float item_a1
for idx in range(l):
if a2[idx] > 0:
item_a2 = a2[idx]
item_a1 = a1[idx]
res += item_a2 * item_a1
return res
函数执行时,a1 和 a2 参数是 python 列表。因此我得到错误:
TypeError: 需要一个类似字节的对象,而不是“列表”
我只需要进行这样的计算即可。但是,如果我需要使用 C 最大化加速,我应该如何定义输入参数 float[:] a1 和 float[:] a2?
可能需要手动将列表转换为数组?
附:如果您还可以向我解释是否有必要明确声明 cdef float item_a2 以执行乘法(就性能而言)或者它与 result += a2[idx] * a1[idx] 相同,我将不胜感激
【问题讨论】: