PythiloLesson 7 of 15 · progress kept in this browser

Profiling with cProfile

Timing says how slow a program is. A profiler says where the time goes: it records every function call, how often each function ran, and the time spent in it.

import cProfile
import pstats

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

prof = cProfile.Profile()
prof.runcall(fib, 20)
stats = pstats.Stats(prof)
stats.sort_stats("cumulative")
stats.print_stats(3)
Your task

Write count_calls(func, *args) that runs func(*args) under a cProfile.Profile and returns (result, calls), where calls maps the name of each Python function that ran to its total number of calls as an int. Leave out built-ins, whose file_name in get_stats_profile() is "~".