如何对Python程序进行性能剖析和优化?

进阶Python

答题要点

# cProfile标准剖析
import cProfile
import pstats

profiler = cProfile.Profile()
profiler.enable()
# 运行代码
result = process_data(data)
profiler.disable()

stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20)

# 命令行使用
# python -m cProfile -s cumulative script.py

# line_profiler逐行分析
# @profile
def slow_function():
    result = []
    for i in range(1000):
        result.append(i ** 2)
    return result

# kernprof -l -v script.py

# memory_profiler内存分析
from memory_profiler import profile

@profile
def memory_intensive():
    data = [i for i in range(1000000)]
    return sum(data)

# 时间测量
import time
from functools import wraps

def timing(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__}: {elapsed:.4f}s")
        return result
    return wrapper

# py-spy采样剖析(生产环境)
# py-spy record -o profile.svg -- python script.py
# py-spy top --pid 12345

# scalene(CPU+内存+GPU)
# scalene script.py

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题