Cython与NumPy求和整数与浮点数时的显著性能差异
Cython vs NumPy: 一维数组元素求和的性能对比
我最近针对一维数组的元素求和场景,对比了Cython和NumPy的性能表现,得到了两个有意思的结论:
- 处理整数数组时,Cython实现的求和函数比NumPy原生求和快约20%
- 处理浮点数数组时,Cython的求和速度反而比NumPy慢了大约2.5倍
下面是我用到的两个简单Cython求和函数,已经关闭了边界检查和环绕索引优化来最大化性能:
#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
测试时以NumPy内置的
np.sum()函数作为性能对比基准
内容的提问来源于stack exchange,提问作者Ted Petrou
相关产品推荐
相关产品推荐

