如何使用 Python 分析器获取调用树?

问题描述 投票:0回答:5

我曾经使用过一个内置于系统监视器应用程序中的漂亮的 Apple 分析器。只要你的 C++ 代码是用调试信息编译的,你就可以对正在运行的应用程序进行采样,它会打印出一个缩进树,告诉你父函数的时间花在这个函数上的百分比(以及函数体与其他函数调用) .

例如,如果 main 调用

function_1
function_2
,则
function_2
调用
function_3
,然后 main 调用
function_3
:

main (100%, 1% in function body):
    function_1 (9%, 9% in function body):
    function_2 (90%, 85% in function body):
        function_3 (100%, 100% in function body)
    function_3 (1%, 1% in function body)

看到这一点,我会想,“

function_2
主体的代码中有些东西花费了很长时间。如果我希望我的程序更快,那就应该从那里开始。”

如何最轻松地获得 Python 程序的精确分析输出?

我见过有人说这样做:

import cProfile, pstats
prof = cProfile.Profile()
prof = prof.runctx("real_main(argv)", globals(), locals())
stats = pstats.Stats(prof)
stats.sort_stats("time")  # Or cumulative
stats.print_stats(80)  # 80 = how many to print

但是与那个优雅的调用树相比,它相当混乱。如果您可以轻松做到这一点,请告诉我,这会有很大帮助。

python tree profiling
5个回答
85
投票

我也偶然发现了这一点,并花了一些时间学习如何生成调用图(cProfile 的正常结果并没有提供太多信息)。将来的参考,这是使用 cProfile + gprof2dot + graphViz 生成漂亮的调用树图形的另一种方法。

————————

  1. 安装 GraphViz:http://www.graphviz.org/Download_macos.php
  2. easy_install gprof2dot
  3. 对代码运行配置文件。

    python -m cProfile -o myLog.profile <myScript.py> arg1 arg2 ...
    
  4. 运行 gprof2dot 将调用配置文件转换为点文件

    gprof2dot -f pstats myLog.profile -o callingGraph.dot
    
  5. 使用graphViz打开以可视化图表

这就是最终结果! 图表采用颜色编码 - 红色表示时间更集中。

Graph is color-coded- red means higher concentration of time


28
投票

我最近想要同样的事情,所以我尝试自己实现一个。

该项目位于 GitHub 上,https://github.com/joerick/pyinstrument

使用方法如下:

from pyinstrument import Profiler

profiler = Profiler()
profiler.start()

# Code you want to profile

profiler.stop()

print(profiler.output_text())

12
投票

gprof2dot
方法可以很好地提取所有信息,所以我是它的粉丝。然而,有时我想查看调用树中的计时数据,所以我创建了tuna

安装

pip install tuna

并显示您的个人资料

tuna program.prof

10
投票

查看此库 http://pycallgraph.slowchop.com/ 以获取调用图。效果非常好。如果您想分析特定功能,请查看 http://mg.pov.lt/blog/profiling.html

这是 profilehooks 模块的结果。

alt text


0
投票

您可以使用SnakeViz

pip install snakeviz

创建配置文件:

python -m cProfile -o program.prof my_program.py

生成交互式图表:

snakeviz program.prof

© www.soinside.com 2019 - 2024. All rights reserved.