[英]Efficient math ops on small arrays in python with cython
我使用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包裝並使用ndarrays,但是與使用malloc創建C數組相比,創建它們對於小型1D數組來說似乎非常昂貴(但內存處理變得很麻煩)。
謝謝!
您可以使用基本功能滾動您的簡單自己,這里的檢查是一個模型開始:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.