如何设计一个基于cProfile的性能监控工具,实现自动化性能分析与报告生成?请提供代码框架。
import cProfile
import pstats
import io
import time
from datetime import datetime
class PerformanceMonitor:
"""
基于cProfile的性能监控工具,用于自动化性能分析与报告生成。
功能:
1. 记录函数运行时间
2. 生成性能分析报告
3. 支持多次运行并比较性能
"""
def __init__(self, output_file='performance_report.txt'):
"""
初始化性能监控工具。
:param output_file: 报告输出文件路径
"""
self.output_file = output_file
self.profiler = cProfile.Profile()
def start_monitoring(self):
"""
开始性能监控。
"""
self.profiler.enable()
print("性能监控已启动。")
def stop_monitoring(self, function_name=None):
"""
停止性能监控并生成报告。
:param function_name: 被监控的函数名称
"""
self.profiler.disable()
s = io.StringIO()
ps = pstats.Stats(self.profiler, stream=s).sort_stats('cumulative')
ps.print_stats()
with open(self.output_file, 'a') as f:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
f.write(f"\n=== 性能报告 [{timestamp}] ===\n")
if function_name:
f.write(f"函数: {function_name}\n")
f.write(s.getvalue())
print(f"性能报告已生成并保存至 {self.output_file}。")
@staticmethod
def measure_time(func):
"""
装饰器:记录函数运行时间。
:param func: 被装饰的函数
:return: 装饰后的函数
"""
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"函数 {func.__name__} 运行时间: {end_time - start_time:.6f} 秒")
return result
return wrapper
# 示例使用
if __name__ == '__main__':
monitor = PerformanceMonitor()
@monitor.measure_time
def example_function(n):
"""示例函数:计算从1到n的平方和。"""
total = 0
for i in range(1, n + 1):
total += i * i
return total
monitor.start_monitoring()
result = example_function(100000)
monitor.stop_monitoring('example_function')
print(f"计算结果: {result}")
设计思路
- 核心功能:使用
cProfile 模块对代码进行性能分析,生成详细的性能报告。
- 装饰器:通过
measure_time 装饰器,可以方便地为函数添加运行时间记录功能。
- 报告生成:将性能分析结果写入指定的文件中,支持多次运行的记录。
- 时间戳:每次报告生成时添加时间戳,便于跟踪性能变化。
示例说明
PerformanceMonitor 类封装了性能监控的核心逻辑。
start_monitoring 和 stop_monitoring 分别用于启动和停止性能监控。
measure_time 装饰器可以轻松地为函数添加性能测试功能。
- 示例函数
example_function 展示了如何使用装饰器记录运行时间。
注意事项
- 性能监控可能会对代码运行速度产生轻微影响,建议仅在测试阶段使用。
- 报告文件默认追加模式,避免覆盖之前的结果。
- 可以通过调整
sort_stats 参数来优化报告内容。