104

I'm using python -m cProfile -s calls myscript.py

python -m cProfile -s percall myscript.py does not work.

The Python documentation says "Look in the Stats documentation for valid sort values.": http://docs.python.org/library/profile.html#module-cProfile, which I cannot find.

Brandon O'Rourke
  • 24,165
  • 16
  • 57
  • 58

1 Answers1

144

-s only uses the keys found under sort_stats.

calls (call count)
cumulative (cumulative time)
cumtime (cumulative time)
file (file name)
filename (file name)
module (file name)
ncalls (call count)
pcalls (primitive call count)
line (line number)
name (function name)
nfl (name/file/line)
stdname (standard name)
time (internal time)
tottime (internal time)

Here's an example

python -m cProfile -s tottime myscript.py
Joshua Olson
  • 3,675
  • 3
  • 27
  • 30
  • 10
    Just to clear it up, for noobs like me, you don't use the quotes :) So an example to sort methods by time spent in the method is "python -m cProfile -s tottime myscript.py" – Stan Tatarnykov Feb 05 '16 at 22:30
  • 6
    There's nothing wrong with using quotes (at least in bash), is there? The quotes are eaten by bash command preprocessing.. – Jindra Helcl Feb 10 '16 at 15:50
  • 2
    As far as windows is concerned, one cannot use the quotes. Also to be noted - sort by time and tottime is one and the same thing. – Susa Apr 03 '18 at 12:57
  • 1
    I want to be able to sort the cprofile output by any of the columns provided. As far as I know, currently it is still not possible to sort it by the column labeled `percall`. – Jeyekomon May 24 '21 at 12:56
  • What is the percall column? You are able to sort on any column. https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats As a last resort you could use the index of the column`For backward-compatibility reasons, the numeric arguments -1, 0, 1, and 2 are permitted.` – Joshua Olson Jun 01 '21 at 17:39
  • @JoshuaOlson your link to the docs.python makes no mention of sorting by percall. It seems odd to me that even though the percall is the most useful sorting column, yet it is not implemented. – berniethejet Aug 21 '21 at 18:53
  • I suspect it isn't included because it is a hybrid/derived metric. This seems like a straightforward thing to be able to add. And python is always happy to accept new features if you want to submit a pull request. https://github.com/python/cpython/blob/main/Lib/pstats.py – Joshua Olson Aug 23 '21 at 14:29
  • Yes it's computed in `Stats.print_line` of `pstats.py`, which prints the information after it has been sorted. But you could also just write your own primitive printer: an instance of `Stats` has a `dict()` in the `.stats` field where the keys are function names. After looking at `_lsprof.c` it seems the values in the `dict()` are tuples of: (, , – mondaugen Aug 27 '21 at 15:26