当 Python 程序的性能无法满足需求时,很多人第一反应是"换语言"。 但实际上通过科学的性能分析和有针对性的优化,Python 程序性能往往能提升数倍甚至数十倍。
第一步:定位瓶颈
优化的第一原则是:不要猜测,要测量。
cProfile 宏观分析
import cProfile, pstats
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats("cumulative")
stats.print_stats(10)
line_profiler 逐行分析
# pip install line_profiler
@profile
def slow_function():
data = []
for i in range(10_000_000):
data.append(str(i))
if i % 1000 == 0:
data.sort() # 性能杀手!
return data
# $ kernprof -lv script.py
第二步:算法与数据结构优化
# 用 set 做成员检查 → O(1) vs list O(n)
items = set(range(1_000_000))
if 500_000 in items: # 快 100 倍以上
# 用 join 拼接字符串
result = "".join(words) # vs result += word
# 用 deque 模拟队列
from collections import deque
queue = deque()
queue.popleft() # O(1) vs list.pop(0) O(n)
第三步:善用内置函数
# 列表推导式(约 2 倍快于 for 循环)
squares = [i * i for i in range(1_000_000)]
# itertools 链式处理
for item in itertools.chain(list1, list2, list3):
process(item)
第四步:Cython 编写扩展
# fibonacci_cy.pyx
def fibonacci_cy(int n):
cdef int i
cdef long long a = 0, b = 1
for i in range(n):
a, b = b, a + b
return a
# 纯 Python: ~8.5s, Cython: ~0.03s (快 280 倍)
第五步:多进程并行
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(count_primes, s, e) for s, e in ranges]
total = sum(f.result() for f in futures)
注意:多进程适合 CPU 密集型任务。I/O 密集型优先考虑 asyncio。
第六步:内存优化
# __slots__ 减少约 30% 内存
class PointSlots:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
# array 模块存大量同类型数据(内存仅为 list 的 1/4)
import array
arr = array.array("d", [1.0, 2.0, 3.0])
优化清单
- 先测量,再优化
- 选择正确的数据结构
- 优先使用内置函数
- 计算密集用 Cython 或 NumPy
- CPU 密集用多进程,I/O 密集用异步
- 大量对象用 __slots__
总结
真正的性能瓶颈往往只存在于 5% 的代码中——找到它,优化它,其他的保持简单即可。
← 返回首页