NumPy向量化运算:把你的代码加速100倍
Lisa Tan | 2026-07-24T12:49:00 | Python, AI
用NumPy向量化运算替代Python for循环,实际测试加速50-100倍的经验分享
# NumPy向量化运算:把你的代码加速100倍 同事的数据处理脚本跑了2小时,我用NumPy重写后只要1分钟。秘诀就两个字:**向量化**。 ## 对比实测 ```python import numpy as np import time # 100万个数据点 n = 1000000 a = np.random.rand(n) b = np.random.rand(n) # Python for循环 - 慢 start = time.time() result = [] for i in range(n): result.append(a[i] * b[i] + a[i] ** 2) print("for循环: {:.3f}s".format(time.time() - start)) # 输出:for循环: 0.832s # NumPy向量化 - 快 start = time.time() result = a * b + a ** 2 # 一行搞定 print("向量化: {:.3f}s".format(time.time() - start)) # 输出:向量化: 0.008s # 快了100倍! ``` ## 常见优化模式 ```python # 1. 条件过滤:不要用if,用布尔索引 # 慢 filtered = [x for x in arr if x > 0.5] # 快 filtered = arr[arr > 0.5] # 2. 广播机制:不需要显式循环 # 每行减去行均值(中心化) matrix = np.random.rand(1000, 100) # 慢:for循环逐行处理 # 快:利用广播 centered = matrix - matrix.mean(axis=1, keepdims=True) # 3. 避免临时数组 # 慢:创建多个临时数组 result = np.sqrt(a ** 2 + b ** 2) # 快:用np.hypot result = np.hypot(a, b) ``` 口诀:**能用NumPy的不用for循环,能用ufunc的不用自定义函数**。向量化是Python数值计算的核心技能。