Muh*_*lah 6 python profiling cprofile snakeviz
嗨,我知道使用命令行方法来分析 python 脚本,如下所示。
python -m cProfile -o program.prof my_program.py
但是,我正在使用 cProfile 模块分析 Python 中的特定代码段,如下所示。
import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
Run Code Online (Sandbox Code Playgroud)
如何pr将输出保存cProfile.Profile()到*.profile文件而不是pstats.Stats()用于分析和打印分析结果。因此,我可以使用 SnakeViz 或类似实用程序来直观地分析统计数据。
Profile 类具有将统计信息写入文件的方法。您可以使用它来将输出保存到文件中。
filename = 'profile.prof' # You can change this if needed
pr.dump_stats(filename)
Run Code Online (Sandbox Code Playgroud)