Code

Profile the Slowpoke

Timing tells you how slow something is. A profiler tells you where the time goes. It records every function call: how many times it ran and how long it took.

import cProfile, io, pstats

profiler = cProfile.Profile()
profiler.runcall(survey)          # run survey() while recording

out = io.StringIO()
stats = pstats.Stats(profiler, stream=out)
stats.sort_stats("cumulative").print_stats(5)
print(out.getvalue())

How to read the report:

  • ncalls: how many times the function was called
  • tottime: time spent inside the function itself
  • cumtime: time including everything it called

Sort by "cumulative" to find the expensive branches, or by "tottime" to find the hot spots.

For raw numbers, stats.stats is a dict. Its keys look like (filename, line, function_name) and its values look like (primitive_calls, total_calls, tottime, cumtime, callers).

Pip tip: On your own machine you can profile a whole script with python -m cProfile -s cumulative app.py.

Assignment

  1. profile_report(func, limit=5): profile func() and return the report text, sorted by "cumulative" and limited to limit rows.
  2. calls_to(func, name): profile func() and return how many times a function called name ran (total calls; 0 if it never ran).