小编chr*_*nos的帖子

高效数学运算使用cython在python中的小数组

我使用numpexpr在大型数组上进行快速数学运算,但如果数组的大小小于CPU缓存,则使用简单数组数学在Cython中编写代码会更快,尤其是如果多次调用该函数.

问题是,你如何在Cython中使用数组,或者更明确地说:在Cython中是否有Python的array.array类型的直接接口?我想做的是这样的事(简单例子)

cpdef array[double] running_sum(array[double] arr):
    cdef int i 
    cdef int n = len(arr)
    cdef array[double] out = new_array_zeros(1.0, n)
    ... # some error checks
    out[0] = arr[0]
    for i in xrange(1,n-1):
        out[i] = out[i-1] + arr[i]

    return(out)
Run Code Online (Sandbox Code Playgroud)

我首先尝试使用Cython numpy包装并使用ndarrays,但是与使用malloc创建C数组相比,创建它们对于小型1D数组来说似乎非常昂贵(但内存处理变得很麻烦).

谢谢!

python arrays performance numpy cython

9
推荐指数
1
解决办法
1572
查看次数

标签 统计

arrays ×1

cython ×1

numpy ×1

performance ×1

python ×1