Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

How can you get the call tree with Python profilers?

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).

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)

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."

How can I most easily get this exact profiling output for a Python program?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just stumbled on this as well, and spent some time learning how to generate a call graph (the normal results of cProfile is not terribly informative). Future reference, here's another way to generate a beautiful call-tree graphic with cProfile + gprof2dot + graphViz.

———————

  1. Install GraphViz: http://www.graphviz.org/Download_macos.php
  2. easy_install gprof2dot
  3. Run profile on the code.

    python -m cProfile -o myLog.profile <myScript.py> arg1 arg2 ...
    
  4. Run gprof2dot to convert the call profile into a dot file

    gprof2dot -f pstats myLog.profile -o callingGraph.dot
    
  5. Open with graphViz to visualize the graph

Here's what the end result would look like! Graph is color-coded- red means higher concentration of time.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...