I'm profiling in Python using cProfile
. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?
EDIT:
I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
You might want to take a look at pycallgraph.
Pycscope does this. I just found it today, so I can't speak to how good it is, but the few examples I've tried have been pretty good (though not perfect).
https://pypi.python.org/pypi/pycscope/
You would use this to generate a cscope file and then a cscope plugin from an editor, VIM specifically. I tried using it with vanilla cscope, it seems that plain cscope gets confused.
I have not used cProfile myself, but most profilers give you a call hierarchy.
Googling I found this slides about cProfile. Maybe that helps. Page 6 looks like cProfile does provide a hierarchy.
I almost always view the output of the cProfile module using Gprof2dot, basically it converts the output into a graphvis graph (a
.dot
file), for example:It makes it very easy to determine which function is slowest, and which function[s] called it.
Usage is:
That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.
There is a workaround to get the caller function:
You can add as many f_back as you want in case you want the caller caller etc If you want to calculate frequent calls you can do this:
Then print them by order of frequency:
It is possible to do it using profiler
cProfile
in standard library.In
pstats.Stats
(the profiler result) there is methodprint_callees
(or alternativelyprint_callers
).Example code:
Result will be something like:
On the left you have the caller, on the right you have the callee.
(for example
_fixtext
was called from_data
47827 times and from_start_list
46429 times)See also:
Couple of notes:
(i.e. not possible to use from command line like
python -m cProfile myscript.py
. Though it is possible to write separate script for that)strip_dirs()
must go beforesort_stats()
(otherwise sorting does not work)