本文目录导读:

优化Python案例的执行速度可以从多个层面入手,常见的优化策略包括以下几个方面:
代码层面的优化
使用合适的数据结构
# 避免使用列表进行频繁的查找操作
# 慢速:列表查找 O(n)
items = [1, 2, 3, 4, 5]
if 3 in items: # O(n) 操作
pass
# 快速:集合查找 O(1)
items_set = {1, 2, 3, 4, 5}
if 3 in items_set: # O(1) 操作
pass
避免不必要的循环嵌套
# 慢速:多重循环
result = []
for i in range(1000):
for j in range(1000):
result.append(i * j)
# 快速:列表推导式
result = [i * j for i in range(1000) for j in range(1000)]
使用局部变量
# 慢速:频繁访问全局变量
def slow_function():
import math
total = 0
for i in range(1000000):
total += math.sqrt(i) # 每次都要查找math
# 快速:使用局部变量
def fast_function():
from math import sqrt
total = 0
sqrt_local = sqrt # 创建局部引用
for i in range(1000000):
total += sqrt_local(i)
算法优化
选择合适的算法
# 慢速:冒泡排序 O(n²)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# 快速:内置排序 O(n log n)
arr.sort()
# 对于大量数据,考虑使用更高效的算法
from bisect import insort # 二分插入
缓存计算结果
# 使用 functools.lru_cache 装饰器
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
使用内置函数和模块
利用Python标准库
# 慢速:手动实现
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
# 快速:内置函数
sum(numbers)
# 使用 collections 模块
from collections import Counter, defaultdict, deque
# 使用 itertools 模块
from itertools import chain, groupby, permutations
并行和并发
多线程(I/O密集型任务)
import threading
def io_task(filename):
with open(filename, 'r') as f:
content = f.read()
threads = []
for file in files:
t = threading.Thread(target=io_task, args=(file,))
threads.append(t)
t.start()
for t in threads:
t.join()
多进程(CPU密集型任务)
from multiprocessing import Pool
def cpu_intensive_task(x):
return x ** 2
with Pool(processes=4) as pool:
results = pool.map(cpu_intensive_task, range(1000000))
使用第三方库
NumPy (数值计算)
import numpy as np # 慢速:纯Python循环 result = [x * 2 for x in range(1000000)] # 快速:NumPy向量化操作 arr = np.arange(1000000) result = arr * 2
Numba (即时编译)
from numba import jit
@jit(nopython=True)
def fast_calculation(n):
total = 0
for i in range(n):
total += i ** 2
return total
Cython
# example.pyx
def cython_function(int n):
cdef int i
cdef int total = 0
for i in range(n):
total += i * i
return total
性能分析工具
使用cProfile定位瓶颈
import cProfile
def my_function():
# 你的代码
pass
cProfile.run('my_function()', sort='cumtime')
使用timeit测量微性能
import timeit
time = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
print(f"执行时间: {time} 秒")
实践建议
- 先测量,后优化:使用性能分析工具找出真正的瓶颈
- 优化最慢的部分:遵循80/20法则
- 优先优化算法:算法改进往往比微优化效果更显著
- 考虑内存使用:合理的内存管理可以提升性能
- 使用生成器处理大数据:减少内存占用
示例:综合优化方案
from functools import lru_cache
import numpy as np
from concurrent.futures import ThreadPoolExecutor
class OptimizedProcessor:
def __init__(self):
self.cache = {}
@lru_cache(maxsize=1000)
def expensive_operation(self, n):
# 使用NumPy加速数值计算
return np.sum(np.arange(n) ** 2)
def process_batch(self, data):
# 并行处理批次数据
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(self.expensive_operation, data))
return results
# 使用局部变量优化
process_func = OptimizedProcessor().process_batch
优化的目的是在可读性和性能之间取得平衡,通常建议先编写清晰、正确的代码,然后根据实际需要进行优化。