Python pstats 模块
实例
直接对函数进行性能分析并打印前几行结果(无需文件):
import cProfile, pstats
def work():
s = 0
for i in range(20000):
s += i*i
return s
pr = cProfile.Profile()
pr.enable()
work()
pr.disable()
pstats.Stats(pr).strip_dirs().sort_stats("time").print_stats(5)
亲自试一试 »
定义和用法
pstats 模块读取并报告由 profile 或 cProfile 生成的性能分析数据。
使用它来对耗时最长的函数进行排序和打印,并比较多次运行的结果。
成员
| 成员 | 描述 |
|---|---|
| Stats | 用于加载和分析性能分析结果的主类。 |
| Stats.add() | 合并来自其他统计文件或Stats对象的数据。 |
| Stats.print_callers() | 打印被分析函数的调用者。 |
| Stats.print_callees() | 打印被分析函数的被调用者。 |
| Stats.print_stats() | 打印汇总表(您可以指定要显示的行数)。 |
| Stats.sort_stats() | 按键排序,例如 time、cumulative 或 calls。 |
| Stats.strip_dirs() | 移除路径前缀以缩短输出中的文件名。 |

