使用 cython 在 python 中对小数组进行高效数学运算

2024-01-16

我使用 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)

我首先尝试使用 Cython numpy 包装器并使用 ndarray,但与使用 malloc 创建 C 数组相比,对于小型一维数组来说,创建它们似乎成本非常高(但内存处理变得很痛苦)。

Thanks!


您可以使用基本功能来创建简单的自己的功能,并检查这里是否是一个可以开始的模型:

from libc.stdlib cimport malloc,free

cpdef class SimpleArray:
    cdef double * handle
    cdef public int length
    def __init__(SimpleArray self, int n):
        self.handle = <double*>malloc(n * sizeof(double))
        self.length = n
    def __getitem__(self, int idx):
        if idx < self.length:
            return self.handle[idx]
        raise ValueError("Invalid Idx")
    def __dealloc__(SimpleArray self):
        free(self.handle) 

cpdef SimpleArray running_sum(SimpleArray arr):
    cdef int i 
    cdef SimpleArray out = SimpleArray(arr.length)

    out.handle[0] = arr.handle[0]
    for i from 1 < i < arr.length-1:
        out.handle[i] = out.handle[i-1] + arr.handle[i]
    return out

可以用作

>>> import test
>>> simple = test.SimpleArray(100)
>>> del simple
>>> test.running_sum(test.SimpleArray(100))
<test.SimpleArray object at 0x1002a90b0>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 cython 在 python 中对小数组进行高效数学运算 的相关文章

随机推荐