相关疑难解决方法(0)

在Cython与NumPy中总和int和浮点数时的性能差异很大

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

python numpy cython

12
推荐指数
1
解决办法
464
查看次数

标签 统计

cython ×1

numpy ×1

python ×1