Search code examples
pythonprofilingprofiler

Python - Sort profile report by tottime


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?


Solution

  • 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}