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

2024-06-08 08:52:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾经使用一个很好的Apple profiler,它内置在系统监视器应用程序中。只要C++代码是用调试信息编译的,就可以对运行的应用程序进行采样,并打印出缩进树,告诉您在该函数中使用父函数的时间百分比(以及体与其他函数调用)。

例如,如果main调用function_1function_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

但和那棵优雅的呼叫树相比,它相当凌乱。请让我知道,如果你能轻松做到这一点,这将有很大帮助。


Tags: 函数代码in程序应用程序applemainstats
3条回答

查看此库http://pycallgraph.slowchop.com/以获取调用图。它工作得很好。如果要分析特定函数,请签出http://mg.pov.lt/blog/profiling.html

这是profilehooks模块的结果。

alt text

我最近也想要同样的东西,所以我试着自己实现一个。

项目在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())

我也无意中发现了这一点,花了一些时间来学习如何生成调用图(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

相关问题 更多 >