
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 calledtottime: time spent inside the function itselfcumtime: 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
profile_report(func, limit=5): profilefunc()and return the report text, sorted by"cumulative"and limited tolimitrows.calls_to(func, name): profilefunc()and return how many times a function callednameran (total calls; 0 if it never ran).
profile_report(func, limit=5): profilefunc()and return the report text, sorted by"cumulative"and limited tolimitrows.calls_to(func, name): profilefunc()and return how many times a function callednameran (total calls; 0 if it never ran).
main.py Python sleeping
Press Run to try your code, then Check to test it.