Python – Sort profile report by tottime

Question:

Python includes a simple to use profiler:

>> import cProfile
>> import re
>> cProfile.run('re.compile("foo|bar")')

      197 function calls (192 primitive calls) in 0.002 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 re.py:212(compile)
    ...

How can do the exact same thing, but sorted by tottime instead of standardname?

Asked By: SRobertJames

||

Answers:

Use the sort=... argument of cProfile.run:

>>> import cProfile
>>> import time
>>> cProfile.run('time.sleep(1); time.monotonic()', sort='tottime')

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    1.001    1.001    1.001    1.001 {built-in method time.sleep}
        1    0.000    0.000    1.001    1.001 {built-in method builtins.exec}
        1    0.000    0.000    1.001    1.001 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {built-in method time.monotonic}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
Answered By: Błażej Michalik

You can also sort by tottime when running cProfile from the command line like this:

python -m cProfile -s tottime my_script.py
Answered By: Caridorc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.