# pstats-性能分析
# 概述
pstats是Python标准库中的一个模块,用于对cProfile性能分析结果进行统计和展示。
pstats模块提供了一系列函数和类,可以用于读取和处理cProfile性能分析结果,生成统计报告,并以多种格式进行展示。其中,常用的函数和类包括:
- pstats.Stats:用于读取和处理cProfile性能分析结果的类;
- pstats.sort_stats():用于按照指定的方式对性能分析结果进行排序;
- pstats.print_stats():用于输出性能分析结果的函数;
- pstats.dump_stats():用于将性能分析结果保存到文件的函数;
- pstats.load_stats():用于从文件中读取性能分析结果的函数;
- pstats.Stats.strip_dirs():用于去掉函数名中的路径信息;
- pstats.Stats.sort_stats():用于按照指定的方式对性能分析结果进行排序;
- pstats.Stats.print_stats():用于输出性能分析结果的方法;
- pstats.Stats.print_callees():用于输出调用了指定函数的函数列表;
- pstats.Stats.print_callers():用于输出被指定函数调用的函数列表。
# 使用示例
在以下示例中,我们定义了两个函数func1和func2,分别模拟了一些计算密集型的操作。然后,在主函数main中,我们多次调用这两个函数,模拟了一些计算密集型的场景。最后,我们使用cProfile.run()函数对主函数进行性能分析,并将分析结果保存到文件result.stats中。然后,我们使用pstats.Stats类读取分析结果,并按照累计时间进行排序,输出性能分析报告。
import cProfile
import pstats
def func1():
for i in range(1000000):
pass
def func2():
for i in range(2000000):
pass
def main():
for i in range(5):
func1()
for i in range(3):
func2()
if __name__ == '__main__':
cProfile.run('main()', 'result.stats')
p = pstats.Stats('result.stats')
p.strip_dirs().sort_stats('cumulative').print_stats()
"""
Tue Mar 28 18:23:46 2023 result.stats
12 function calls in 0.259 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.259 0.259 {built-in method builtins.exec}
1 0.000 0.000 0.259 0.259 <string>:1(<module>)
1 0.000 0.000 0.259 0.259 cprofile_test_pstats.py:12(main)
3 0.149 0.050 0.149 0.050 cprofile_test_pstats.py:8(func2)
5 0.110 0.022 0.110 0.022 cprofile_test_pstats.py:4(func1)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
"""