Part 1. How to measure the running time of a program#

In Python the same result can be computed in many ways, and the running times of different programs can differ by several orders of magnitude. Before we start speeding programs up, we must be able to measure time fairly: compare only programs that compute the same thing, and do it so that the result does not depend on chance. The guiding example of this part comes from the instructor’s study of Python performance. It consists of two short programs that sum \(i+j\) over all pairs \(0\le i,j<100\). We checked a similar sum in Lecture 1 (§1.2), when we compared the sum \(1+2+\dots+n\) with Gauss’s formula.

Two programs, the same result#

The first program adds up the terms in two nested for loops. The second passes a generator expression, which yields the successive terms, to the function sum.

suma = 0
for i in range(100):
    for j in range(100):
        suma += i + j
print(suma)

print(sum(i + j for i in range(100) for j in range(100)))
990000
990000

Both programs print the same number, and this is no coincidence. In the sum over all pairs, each value of \(i\) occurs \(n\) times, and so does each value of \(j\), so

\[ S(n)=\sum_{i=0}^{n-1}\sum_{j=0}^{n-1}(i+j)=2n\sum_{i=0}^{n-1}i=2n\cdot\frac{n(n-1)}{2}=n^2(n-1). \]

SymPy, which can sum symbolically, will carry out the same computation:

import sympy as sp

i, j, n = sp.symbols("i j n", integer=True, nonnegative=True)
S = sp.summation(sp.summation(i + j, (j, 0, n - 1)), (i, 0, n - 1))
print("S(n) =", sp.factor(S), "  S(100) =", S.subs(n, 100))
S(n) = n**2*(n - 1)   S(100) = 990000

The formula \(S(n)=n^2(n-1)\) is a contract: it says what every variant of the program must compute. Before comparing times, we will always check that the variants give the same result, because otherwise we would be comparing different tasks. The formula itself is also a variant of the program, and the fastest one at that, but we will get to it at the end of this part.

One measurement is not enough#

The simplest clock in Python is time.perf_counter(): it returns the number of seconds elapsed since a certain moment and is good only for subtracting two readings. Let us wrap the first program in a function and measure a call to it five times.

import time


def suma_petla(n):
    s = 0
    for i in range(n):
        for j in range(n):
            s += i + j
    return s


for _ in range(5):
    start = time.perf_counter()
    suma_petla(100)
    print(f"{(time.perf_counter() - start) * 1e6:.1f} µs")
128.0 µs
123.7 µs
121.2 µs
123.0 µs
124.4 µs

The results differ, although the program computes the same thing every time. The time is affected by other programs running at the same moment, by the state of the processor’s cache, and by changes in its clock frequency. The first call is often slower than the following ones, because since version 3.11 the CPython interpreter adapts bytecode instructions to the data types it sees (the specializing adaptive interpreter, PEP 659), so the code “warms up” during its first executions. A single measurement is therefore not enough: we measure many times and report the median.

%timeit in the notebook and the timeit module#

In a Jupyter notebook the most convenient tool is the “magic” command %timeit. It chooses the number of repetitions by itself and reports the mean with the standard deviation.

%timeit suma_petla(100)
121 μs ± 2.31 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

The command ran the function many times, in seven series. Outside a notebook, the same is provided by the timeit module of the standard library, and in a terminal by the command python -m timeit. For the duration of the measurement, the timeit module turns off the garbage collector and runs the measured code inside a function. We will see in a moment why this second detail matters.

A tool for comparisons#

In this chapter we compare several variants of the same computation at a time, so a table is more convenient than separate %timeit calls. Here is the whole tool. A copy of this cell appears (collapsed) at the beginning of parts 2–7 and 9.

# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.
import platform
import statistics
import subprocess
import sys
import textwrap
import timeit
from importlib.metadata import version

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter

INDYGO, BURSZTYN, ZIELEN = "#4f46e5", "#d97706", "#059669"
SZARY, TUSZ, SIATKA = "#94a3b8", "#334155", "#e2e8f0"
JEDNOSTKI = (("s", 1.0), ("ms", 1e-3), ("µs", 1e-6), ("ns", 1e-9))


def zmierz(f, *args, cel=0.02, proby=7):
    """Mediana czasu jednego wywołania f(*args), w sekundach.

    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo
    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.
    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne
    programy.
    """
    zegar = timeit.Timer(lambda: f(*args))
    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena
    if t > cel:                         # wolna funkcja: trzy wywołania
        return statistics.median(zegar.repeat(repeat=3, number=1))
    n = 1
    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją
        n *= 10
        t = zegar.timeit(number=n)
    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s
    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n


def czas(s):
    """Czas w sekundach jako napis z jednostką, np. 1.23 ms."""
    for jednostka, skala in JEDNOSTKI:
        if s >= 0.9995 * skala or jednostka == "ns":
            v = s / skala
            if v >= 99.95:
                return f"{v:.0f} {jednostka}"
            return f"{v:#.3g} {jednostka}"


def krotnosc(r):
    """Iloraz czasów jako napis: 340×, 2.5×, 0.81×."""
    if r >= 10:
        return f"{r:.0f}×"
    return f"{r:.1f}×" if r >= 1 else f"{r:.2f}×"


def porownaj(warianty, *args, zgodne=None):
    """Mierzy warianty (nazwa → funkcja) na tych samych danych.

    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem
    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to
    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas
    danego. Zwraca słownik czasów.
    """
    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}
    wzorzec = next(iter(wyniki.values()))
    for nazwa, w in wyniki.items():
        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):
            raise AssertionError(f"wariant „{nazwa}” daje inny wynik")
    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}
    baza = next(iter(czasy.values()))
    szer = max(len(nazwa) for nazwa in czasy)
    wiersze = [f"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}"]
    for nazwa, t in czasy.items():
        wiersze.append(f"{nazwa:{szer}}  {czas(t):>9}"
                       f"  {krotnosc(baza / t):>14}")
    print("\n".join(wiersze))
    return czasy


def srodowisko(*biblioteki):
    """Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki."""
    if sys.platform == "darwin":
        procesor = subprocess.run(
            ["sysctl", "-n", "machdep.cpu.brand_string"],
            capture_output=True, text=True).stdout.strip()
        system = f"macOS {platform.mac_ver()[0]}"
    else:
        procesor = platform.processor()
        system = f"{platform.system()} {platform.release()}"
    opis = [procesor or platform.machine(), system,
            f"Python {platform.python_version()}"]
    opis += [f"{b} {version(b)}" for b in biblioteki]
    print(textwrap.fill("Pomiary: " + ", ".join(opis), width=79,
                        subsequent_indent="  "))


def upewnij(warunek, tresc):
    """Pilnuje zdań z tekstu rozdziału.

    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.
    """
    if not warunek:
        raise AssertionError(f"Tekst rozdziału twierdzi: {tresc}. "
                             "Pomiar temu przeczy.")


def _os_czasu(v, _):
    for jednostka, skala in JEDNOSTKI:
        if v >= 0.9995 * skala:
            return f"{v / skala:.0f} {jednostka}"
    return f"{v / 1e-9:g} ns"


def wykres_czasow(czasy, tytul):
    """Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony."""
    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze
    t = [czasy[nazwa] for nazwa in nazwy]
    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))
    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors="white",
               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])
    for i, v in enumerate(t):
        ax.annotate(czas(v), (v, i), xytext=(9, 0), va="center",
                    textcoords="offset points", fontsize=9, color=TUSZ)
    ax.set_yticks(range(len(nazwy)), nazwy)
    ax.set_xscale("log")
    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety
    ax.xaxis.set_major_locator(LogLocator(base=10))
    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.grid(axis="x", color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right", "left"):
        ax.spines[bok].set_visible(False)
    ax.tick_params(axis="y", length=0)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()


def wykres_skalowania(rozmiary, serie, tytul, opis_x="n"):
    """Czas w zależności od rozmiaru danych, obie osie logarytmiczne."""
    fig, ax = plt.subplots(figsize=(8, 4))
    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), "osD")
    for (nazwa, czasy_serii), kolor, znak in style:
        ax.loglog(rozmiary, czasy_serii, "-", marker=znak, color=kolor,
                  lw=2, ms=6, label=nazwa)
    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.yaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel(opis_x)
    ax.grid(color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right"):
        ax.spines[bok].set_visible(False)
    ax.legend(loc="best", frameon=False, fontsize=9)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()
  • zmierz(f, *args) calls f(*args) in series lasting about \(0.02\) s and returns the median, over seven series, of the time of a single call. The median does not change when another program disturbs a single series. A slow function (one that takes longer than a series) is called three times.

  • porownaj(warianty, *args) first checks that all variants give the same result, then measures the times and prints a table. The speedup is the time of the first variant divided by the time of the given one; a number less than \(1\) means a slowdown.

  • srodowisko(...) prints the computer and the library versions on which we measure.

  • upewnij(warunek, tresc) guards sentences of the chapter’s text, e.g., “variant A is more than a hundred times faster than B.” Every time the page is built, it checks them against fresh measurements. If a measurement contradicts a sentence, the build stops. These cells are hidden on the page, but they are in the downloaded notebook.

  • wykres_czasow and wykres_skalowania plot the results on logarithmic axes.

srodowisko("sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, sympy 1.14.0

Times in this chapter

All times come from the computer on which this page was built (the line printed by srodowisko above), and they change with every build. On your computer they will be different. Ratios of times usually change much less than the times themselves. Download the notebook (the button at the top of the page) and check what they are on your computer.

A loop in a notebook cell and a loop in a function#

Code typed directly into a notebook cell runs at module level. The variables s, i, j are then global, and the interpreter looks them up in a namespace dictionary. Inside a function the same variables are local, and the interpreter accesses them by their slot number in the call frame. We imitate a notebook cell by compiling the loop and running it with the function exec in a separate namespace dictionary.

ZRODLO = """
s = 0
for i in range(n):
    for j in range(n):
        s += i + j
"""
kod = compile(ZRODLO, "<komórka>", "exec")


def w_module(n):
    nazwy = {"n": n}          # słownik nazw, jak w komórce notatnika
    exec(kod, nazwy)
    return nazwy["s"]


czasy_zakresu = porownaj({"pętla w komórce (poziom modułu)": w_module,
                          "ta sama pętla w funkcji": suma_petla}, 100)
wariant                               czas  przyspieszenie
pętla w komórce (poziom modułu)     296 µs            1.0×
ta sama pętla w funkcji             121 µs            2.4×

The same loop inside a function runs noticeably faster. The reason can be seen in the bytecode, that is, in the instructions that the interpreter executes. The dis module prints them. Let us collect the instructions that read and write variables:

import dis


def rozkazy(obiekt):
    return sorted({r.opname for r in dis.get_instructions(obiekt)
                   if r.opname.startswith(("LOAD", "STORE"))})


print("komórka:", rozkazy(kod))
print("funkcja:", rozkazy(suma_petla))
komórka: ['LOAD_CONST', 'LOAD_NAME', 'STORE_NAME']
funkcja: ['LOAD_CONST', 'LOAD_FAST', 'LOAD_GLOBAL', 'STORE_FAST']

At module level, variables are handled by the instructions LOAD_NAME and STORE_NAME, which look the name up in a dictionary. In a function, the instructions LOAD_FAST and STORE_FAST access a local variable by its number. Only range is a global name in the function (LOAD_GLOBAL), but we read it only when each loop starts, not for every term of the sum. The practical conclusion: wrap computations in functions. The code is then faster, and in addition it is easier to test and to reuse.

For the same reason, %timeit can be misleading. The command pastes the measured code into a function, so a loop typed into a cell with %%timeit is measured as a loop in a function. This can be seen in the source code that the timeit module builds before measuring:

import timeit

print(timeit.Timer(ZRODLO, setup="n = 100").src)
def inner(_it, _timer):
    n = 100
    _t0 = _timer()
    for _i in _it:
        
        s = 0
        for i in range(n):
            for j in range(n):
                s += i + j
        
        pass
    _t1 = _timer()
    return _t1 - _t0
%%timeit n = 100
s = 0
for i in range(n):
    for j in range(n):
        s += i + j
119 μs ± 2.28 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

The time from %%timeit is close to the time of the loop in a function, not of the loop executed in a cell, even though in both cases we typed the loop into a cell. The instructor’s study, which compares four versions of CPython, describes the same effect in detail.

Loop, generator, list, formula#

Let us now compare five ways of computing \(S(n)\), all inside functions:

  1. two nested loops;

  2. a generator passed to the function sum;

  3. a list comprehension passed to the function sum;

  4. the linear sum \(2n\sum_{i<n} i\) from the first step of the proof of the formula;

  5. the formula \(n^2(n-1)\) itself.

The first three variants go through all \(n^2\) pairs, the fourth through \(n\) numbers, and the fifth performs a few arithmetic operations.

def suma_generator(n):
    return sum(i + j for i in range(n) for j in range(n))


def suma_lista(n):
    return sum([i + j for i in range(n) for j in range(n)])


def suma_liniowa(n):
    return 2 * n * sum(range(n))


def suma_wzor(n):
    return n * n * (n - 1)


WARIANTY = {"dwie pętle": suma_petla, "generator w sum": suma_generator,
            "lista w sum": suma_lista, "suma liniowa": suma_liniowa,
            "wzór n²(n-1)": suma_wzor}
czasy_100 = porownaj(WARIANTY, 100)
wariant               czas  przyspieszenie
dwie pętle          117 µs            1.0×
generator w sum     157 µs           0.74×
lista w sum        79.2 µs            1.5×
suma liniowa        265 ns            440×
wzór n²(n-1)       44.8 ns           2604×
czasy_1000 = porownaj(WARIANTY, 1000)
wykres_czasow(czasy_1000, "Pięć sposobów obliczenia S(1000)")
wariant               czas  przyspieszenie
dwie pętle         17.6 ms            1.0×
generator w sum    21.4 ms           0.82×
lista w sum        18.6 ms           0.95×
suma liniowa       5.38 µs           3269×
wzór n²(n-1)       49.7 ns         353606×
../_images/3a8c15805b09f4a35cbbd980e0dbcdf58989e380ace2478aad31d87441302242.png
PRZEGLAD_PAR = ["dwie pętle", "generator w sum", "lista w sum"]
for n_, czasy_n in ((100, czasy_100), (1000, czasy_1000)):
    najszybszy = min(PRZEGLAD_PAR, key=czasy_n.get)
    rozrzut = max(czasy_n[k] for k in PRZEGLAD_PAR) / czasy_n[najszybszy]
    print(f"n = {n_}: najszybszy z przeglądających pary jest „{najszybszy}”,")
    print(f"{'':9}najwolniejszy jest od niego {krotnosc(rozrzut)} wolniejszy")
n = 100: najszybszy z przeglądających pary jest „lista w sum”,
         najwolniejszy jest od niego 2.0× wolniejszy
n = 1000: najszybszy z przeglądających pary jest „dwie pętle”,
         najwolniejszy jest od niego 1.2× wolniejszy

The three variants that go through all pairs differ from one another by less than a factor of four, and which of them wins depends on \(n\) and on the Python version (see the lines below the plot). The instructor’s study shows this in more detail. For small \(n\) the list is often the fastest, because its elements are small integers, which Python keeps in memory permanently. For large \(n\) the program has to create and free \(n^2\) new objects, and the list’s advantage disappears. The last two variants are faster by orders of magnitude: the linear sum more than a hundred times, and the formula more than ten thousand times. Changing the algorithm from \(n^2\) operations to \(n\) or to a constant number of operations gives more than any change in how the loop is written. This lesson is the subject of part 2.

Measurement pitfalls#

It is easy to spoil a time measurement so that it measures something other than we think. Here are the four most common ways.

An exhausted generator. A generator yields each value only once. A second pass computes nothing:

g = (i + j for i in range(100) for j in range(100))
print(sum(g), sum(g))
990000 0

If we measured sum(g) repeatedly with a single generator g, only the first call would compute the sum. The others would sum an empty sequence. That is why in the tables we always measure a call to a function that creates a new generator.

Caches. Some libraries remember results. SymPy remembers the results of many operations, so a second expansion of the same expression takes a fraction of the time of the first:

from sympy.core.cache import clear_cache

x, y = sp.symbols("x y")
w = (x + y + 1)**30
pomiary = []
for _ in range(3):
    start = time.perf_counter()
    sp.expand(w)
    pomiary.append(time.perf_counter() - start)
clear_cache()                       # czyścimy pamięć podręczną SymPy
start = time.perf_counter()
sp.expand(w)
pomiary.append(time.perf_counter() - start)
print("trzy kolejne rozwinięcia:", ", ".join(czas(t) for t in pomiary[:3]))
print("po wyczyszczeniu pamięci podręcznej:", czas(pomiary[3]))
trzy kolejne rozwinięcia: 34.6 ms, 5.38 µs, 1.08 µs
po wyczyszczeniu pamięci podręcznej: 32.9 ms

A repeated measurement on the same data would measure the cache, not the expansion of the polynomial. In part 7 we clear this cache before every SymPy measurement.

One-time costs. Importing a library, compilation, and the first, “cold” call are paid for only once. We measure them separately, starting a new Python process each time:

import statistics
import subprocess
import sys


def uruchom(polecenie):
    start = time.perf_counter()
    subprocess.run([sys.executable, "-c", polecenie], check=True)
    return time.perf_counter() - start


POLECENIA = ("pass", "import math", "import numpy", "import sympy")
importy = {polecenie: statistics.median(uruchom(polecenie) for _ in range(3))
           for polecenie in POLECENIA}
for polecenie, t in importy.items():
    print(f"python -c '{polecenie}'".ljust(28), czas(t))
python -c 'pass'             14.7 ms
python -c 'import math'      13.8 ms
python -c 'import numpy'     44.3 ms
python -c 'import sympy'     159 ms

Starting Python alone takes from a dozen to several dozen milliseconds, and importing SymPy several times longer. For a short script these costs can outweigh the computation. They are not, however, part of the computation time, and they must not be mixed with the time of a single call.

Noise. Let us measure the same function twice, as if it were two different variants:

czasy_szum = porownaj({"suma_petla": suma_petla,
                       "suma_petla jeszcze raz": suma_petla}, 300)
wariant                      czas  przyspieszenie
suma_petla                1.28 ms            1.0×
suma_petla jeszcze raz    1.35 ms           0.95×

The speedup should be \(1\), and it is almost \(1\). The difference is measurement noise. That is why we do not treat differences of a few percent as a result. We are interested in differences by a factor of several or more, and also in how the time grows with the size of the data.

Where the time goes: the profiler#

Before we start speeding up a program, we need to know which part of it takes the time. This is what the profiler cProfile is for: it counts the calls of each function and the time spent in it and in the functions it calls. Let us take the trapezoidal rule for \(\int_0^1 e^{-x^2}\,dx\), in which we compute the values of the function by substitution in SymPy, as in many places in Lecture 5.

import cProfile
import pstats


def trapezy_sympy(n):
    """Metoda trapezów; wartości funkcji przez podstawienie w SymPy (wolno)."""
    x = sp.symbols("x")
    f = sp.exp(-x**2)
    h = sp.Rational(1, n)
    ys = [float(f.subs(x, k * h)) for k in range(n + 1)]
    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n


def profil(f, *args, ile=6):
    """Najdroższe funkcje według czasu łącznego (z wywoływanymi)."""
    clear_cache()
    p = cProfile.Profile()
    p.runcall(f, *args)
    statystyki = pstats.Stats(p).stats
    calosc = max(s[3] for s in statystyki.values())
    print(f"{'wywołań':>8} {'czas łączny':>12}  funkcja")
    wiersze = sorted(statystyki.items(), key=lambda kv: -kv[1][3])
    for (plik, _, nazwa), (_, wywolan, _, laczny, _) in wiersze[:ile]:
        if "site-packages/" in plik:      # funkcja z biblioteki: moduł i nazwa
            nazwa = plik.split("site-packages/")[-1] + ":" + nazwa
        print(f"{wywolan:8} {czas(laczny):>12}  {nazwa}")
    return statystyki, calosc


statystyki, calosc = profil(trapezy_sympy, 200)
w_subs = sum(s[3] for (plik, _, nazwa), s in statystyki.items()
             if nazwa == "subs" and "sympy" in plik)
print(f"podstawienia subs zajęły {w_subs / calosc:.0%} czasu")
 wywołań  czas łączny  funkcja
       1      64.9 ms  trapezy_sympy
    3486      56.3 ms  sympy/core/cache.py:wrapper
     201      54.8 ms  sympy/core/basic.py:subs
    1005      51.8 ms  sympy/core/basic.py:_subs
     402      49.7 ms  sympy/core/basic.py:fallback
     201      26.8 ms  sympy/core/power.py:_eval_subs
podstawienia subs zajęły 84% czasu

The profiler points to the culprit: most of the time is taken by subs, that is, by substituting numbers into a symbolic expression. Our own arithmetic (summing and dividing) hardly matters. So it is the substitution that is worth speeding up, not the loop. In part 7 we will replace subs with the function sp.lambdify, and the same computation will become thousands of times faster.

Summary#

  • First the contract: we compare only variants that give the same result, and we check this before measuring.

  • We measure many times and report the median (%timeit, timeit, our porownaj). Differences of a few percent are noise.

  • Wrap computations in functions: local variables are faster than global ones, and %timeit measures code as if it were in a function anyway.

  • Beware of exhausted generators, library caches, and one-time costs (the import, the first call).

  • Before we start speeding things up, we profile: cProfile shows where the time really goes.

  • Changing the algorithm (here: from \(n^2\) operations to a constant number) gives more than any change in how the loop is written.

Exercises#

  1. ★ Measure suma_petla(n) for \(n=100, 200, 400, 800\). By what factor does the time grow when \(n\) doubles? Explain this by the number of additions performed.

  2. ★ On your computer, check the table of the five variants for \(n=100\) and \(n=3000\). Which of the three variants that go through the pairs wins? Compare with the results on this page.

  3. ★★ Write a variant in which the inner loop is replaced by a formula for the sum \(\sum_{j<n}(i+j)\). How many operations does it perform? Measure it together with the others.

  4. ★★ Measure %timeit sp.expand((x + y + 1)**30) and compare it with a measurement in which you first call clear_cache() in every repetition. Which measurement answers the question “how long does it take to expand the polynomial?”