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

use*_*ser 27 python tree profiling

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

例如,如果main调用function_1and 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)
Run Code Online (Sandbox Code Playgroud)

我会看到这一点,然后想一想,"有些东西需要花费很长时间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
Run Code Online (Sandbox Code Playgroud)

但与优雅的呼叫树相比,它相当混乱.如果你能轻易做到这一点,请告诉我,这会有所帮助.

Max*_*ong 53

我也偶然发现了这一点,花了一些时间学习如何生成一个调用图(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 ...
    
    Run Code Online (Sandbox Code Playgroud)
  4. 运行gprof2dot将调用配置文件转换为点文件

    gprof2dot -f pstats myLog.profile -o callingGraph.dot
    
    Run Code Online (Sandbox Code Playgroud)
  5. 使用graphViz打开以显示图形

这是最终结果的样子!图表采用颜色编码 - 红色表示更高的时间集中度.

图表采用颜色编码 - 红色表示更高的时间集中度

  • [xdot](https://pypi.python.org/pypi/xdot)是.dot文件的一个很好的交互式查看器,可以放大内容. (5认同)
  • 可以在Unix上使用shell命令显示.dot文件,例如"dot callingGraph.dot -Tpng | display"代替步骤5. (4认同)

joe*_*ick 23

我最近想要同样的事情,所以我自己实施了一个.

该项目在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())
Run Code Online (Sandbox Code Playgroud)


Fal*_*rri 10

查看此库http://pycallgraph.slowchop.com/以获取呼叫图表.它工作得很好.如果要查看特定功能,请查看http://mg.pov.lt/blog/profiling.html

这是profilehooks模块的结果.

替代文字

  • 注意:`pycallgraph` 现在没有维护 (2认同)

Nic*_*mer 6

这种gprof2dot方法很好地提取了所有信息,所以我是一个粉丝。但是,有时我想查看调用树中的计时数据,因此我创建了tuna

在此处输入图片说明

安装

pip install tuna
Run Code Online (Sandbox Code Playgroud)

并显示您的个人资料

tuna program.prof
Run Code Online (Sandbox Code Playgroud)

  • 喜欢这个分析器!很容易找到我的瓶颈功能,而且这符合我的直觉。所以金枪鱼工具 5 星 (2认同)