Write your script profiling.py which calls the functions that you want to analysize and run
python -m cProfile -o results.prof profiling.py
After you can analyze the results using the pstats module
import pstats
from pstats import SortKey
old = pstats.Stats('results.prof')
old.sort_stats(SortKey.TIME).print_stats(10)
old.sort_stats(SortKey.TIME).print_stats(5, 'sessions.py') # first get the 5 bigger, then filter on sessions
old.sort_stats(SortKey.TIME).print_stats('sessions.py', 5)
keep an eye out for function calls that should be executed once by each input but are not.
Notes
The files cProfile and profile can also be invoked as a script to profile another script. For example:
tottime
for the total time spent in the given function (and excluding time made in calls to sub-functions)
[...]
cumtime
is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.
Exporting results
To save in raw format, we use dump_stats() method that passes the argument of a directory where the file will be saved and filename. In this tutorial, we save the cProfile output in folder data and filename as cProfileExport.
stats = pstats.Stats(profiler)
stats.dump_stats('../data/cProfileExport')
# export as txt
result = io.StringIO()
stats = pstats.Stats(profiler, stream = result).sort_stats('ncalls')
stats.print_stats()# Save it into disk
with open('../data/cProfileExport.txt', 'w+') as f:
f.write(result.getvalue())
# export as csv
result = io.StringIO()
stats = pstats.Stats(profiler, stream = result).sort_stats('ncalls')
stats.print_stats()
result = result.getvalue()# Chop the string into a csv-like buffer
result = 'ncalls' + result.split('ncalls')[-1]
result = '\n'.join([','.join(line.rstrip().split(None, 6)) for line in result.split('\n')])# Save it into disk
with open('../data/cProfileExport.csv', 'w+') as f:
f.write(result)
Write your script
profiling.py
which calls the functions that you want to analysize and runAfter you can analyze the results using the pstats module
keep an eye out for function calls that should be executed once by each input but are not.
Notes
The files cProfile and profile can also be invoked as a script to profile another script. For example:
Results
tottime is the total time spent in the function alone. cumtime is the total time spent in the function plus all functions that this function called.
The two values is going to be the same if a function never calls anything else.
From the documentation:
Exporting results
To save in raw format, we use dump_stats() method that passes the argument of a directory where the file will be saved and filename. In this tutorial, we save the cProfile output in folder data and filename as cProfileExport.