import cProfile import pstats from io import StringIO def complex_calculation(n): """模拟复杂计算""" result = 0 for i in range(n): for j in range(i): result += i * j return result def data_processing(): """数据处理函数""" data = [complex_calculation(i) for i in range(100, 200)] return sum(data) / len(data) def analyze_with_cprofile(): # 方法1: 使用cProfile.run() profiler = cProfile.Profile() profiler.enable() # 执行要分析的代码 result = data_processing() profiler.disable() # 生成统计报告 stream = StringIO() stats = pstats.Stats(profiler, stream=stream) stats.sort_stats('cumulative') # 按累计时间排序 stats.print_stats(20) # 显示前20行 print("\n=== 详细分析报告 ===") print(stream.getvalue()) return result # 运行分析 analyze_with_cprofile()