29/36
Part 8 of 8 · Follow-upsLearn and do

Why sample at all? cProfile, which records every call, made fib(22) take 4 times as long

Recording every call and return is what cProfile does, and it slows the program down:

import cProfile
import timeit


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


profiler = cProfile.Profile()


def profiled():
    profiler.enable()
    fib(22)
    profiler.disable()


plain = min(timeit.repeat(lambda: fib(22), number=1, repeat=5))
traced = min(timeit.repeat(profiled, number=1, repeat=5))

fib(22) makes 57,313 calls. It took 1.58 ms on its own, and 6.27 ms with cProfile on: 4.0 times as long.

The profile docs set the two side by side. A statistical profiler samples where the program is at random moments and deduces where time is being spent. It reads the stack from outside, so the program runs at full speed. The price is the sampler's blind spot: calls that start and end between two samples.

So use a tracer when you need exact counts and can afford the slowdown. Use a sampler on a production server.

In the editor, write fib_calls(n): how many calls fib(n) makes, built up in a loop. For 22 it's 57,313. Then write cost_per_call_ns(plain_ms, traced_ms, calls): what the tracer added to each call, in nanoseconds.