我使用Cython或NumPy对一维数组中的每个元素求和.当求和整数时, Cython的速度提高了约20%.总结浮点数时,Cython 慢约2.5倍.以下是使用的两个简单函数.
#cython: boundscheck=False
#cython: wraparound=False
def sum_int(ndarray[np.int64_t] a):
cdef:
Py_ssize_t i, n = len(a)
np.int64_t total = 0
for i in range(n):
total += a[i]
return total
def sum_float(ndarray[np.float64_t] a):
cdef:
Py_ssize_t i, n = len(a)
np.float64_t total = 0
for i in range(n):
total += a[i]
return total
Run Code Online (Sandbox Code Playgroud)
创建两个每个包含100万个元素的数组:
a_int = np.random.randint(0, 100, 10**6)
a_float = np.random.rand(10**6)
%timeit sum_int(a_int)
394 µs ± 30 µs per loop (mean ± std. dev. of 7 …
Run Code Online (Sandbox Code Playgroud)