# test.py @profile # 添加装饰器 defslow_function(): data = range(10000) result = [] for x in data: if x % 2 == 0: result.append(x * x) else: result.append(x) return result
1
kernprof -l -v test.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Timer unit: 1e-06 s
File: test.py Function: slow_function at line 2
Line # Hits Time Per Hit % Time Line Contents ============================================================== 2 1 5000.0 5000.0 100.0 @profile 3 1 3000.0 3000.0 60.0 data = range(10000) 4 1 1000.0 1000.0 20.0 result = [] 5 10000 4000.0 0.4 80.0 for x in data: 6 5000 5000.0 1.0 100.0 if x % 2 == 0: 7 5000 3000.0 0.6 60.0 result.append(x * x) 9 5000 2000.0 0.4 40.0 result.append(x)
⚡ perf(Linux 内核性能分析器)
1 2 3
# Linux 系统用 perf perf record -g python your_script.py perf report
perf 可以分析 CPU 缓存命中率、分支预测失误等底层信息。
🧠 常见优化技巧
技巧1:使用局部变量
1 2 3 4 5 6 7 8 9 10 11
# 慢 defslow(): for i inrange(10**6): math.sin(i)
# 快 import math deffast(): sin = math.sin # 局部变量,减少查找 for i inrange(10**6): sin(i)
技巧2:列表推导式 > 循环
1 2 3 4 5 6 7
# 慢 result = [] for x in data: result.append(x * 2)
# 快 result = [x * 2for x in data]
技巧3:使用 slots
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 无 __slots__ classPoint: def__init__(self, x, y): self.x = x self.y = y
# 有 __slots__ classPoint: __slots__ = ('x', 'y') def__init__(self, x, y): self.x = x self.y = y