# 传统Python循环defpython_sum(arr):result =0for num in arr:result += numreturn result# NumPy矢量化import numpy as np
defnumpy_sum(arr):return np.sum(arr)# 性能对比(1000万数据量)
方法
执行时间
加速比
Python循环
1.23s
1x
NumPy矢量化
0.012s
102x
3.2 广播机制图解
四、高性能计算进阶
4.1 内存预分配策略
# 错误示范:动态扩展数组
result = np.empty(0)for i inrange(1000):result = np.append(result, i)# 正确做法:预分配内存
result = np.empty(1000)for i inrange(1000):result[i]= i
4.2 Cython混合编程
# lib.pyx
cimport numpy as cnp
def cython_sum(cnp.ndarray[cnp.double_t, ndim=1] arr):cdef double total = 0cdef int ifor i in range(arr.shape[0]):total += arr[i]return total