如何使用 Python 分析器获取调用树? [英] How can you get the call tree with Python profilers?

查看:67
本文介绍了如何使用 Python 分析器获取调用树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I used to use a nice Apple profiler that is built into the System Monitor application. As long as your C++ code was compiled with debug information, you could sample your running application and it would print out an indented tree telling you what percent of the parent function's time was spent in this function (and the body vs. other function calls).

例如,如果main调用了function_1function_2function_2调用function_3,然后main调用<代码>function_3:

For instance, if main called function_1 and function_2, function_2 calls function_3, and then main calls 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 主体中的代码需要很长时间.如果我希望我的程序更快,那就是我应该开始的地方."

I would see this and think, "Something is taking a long time in the code in the body of function_2. If I want my program to be faster, that's where I should start."

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

我看到有人说要这样做:

I've seen people say to do this:

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

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

But it's quite messy compared to that elegant call tree. Please let me know if you can easily do this, it would help quite a bit.

推荐答案

查看这个库 http://pycallgraph.slowchop.com/ 用于调用图.它真的很好用.如果您想分析特定功能,请查看 http://mg.pov.lt/blog/profiling.html

Check out this library http://pycallgraph.slowchop.com/ for call graphs. It works really well. If you want to profile specific functions, check out http://mg.pov.lt/blog/profiling.html

这是 profilehooks 模块的结果.

This is a result from the profilehooks module.

这篇关于如何使用 Python 分析器获取调用树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆