Part 5. NumPy: the loop moved to C#

A loop in Python pays for every step: the interpreter reads an instruction, checks the types of the objects, and creates a new object for the result. A NumPy array stores numbers of a single type next to one another in memory, and operations on whole arrays are carried out by loops written in C. This style is called vectorization. The programmer is lazy in the best sense: instead of writing a loop, they describe an operation on the whole array, and NumPy writes the loop. In this part we rewrite examples from Lecture 5 (Horner’s scheme, quadrature, Newton basins, the Monte Carlo method) and from Lab 8 (the Game of Life) in this style. At the end we collect the pitfalls: places where NumPy does not help or silently changes the result.

Hide code cell source

# 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()
import math
import random
import sys
import tracemalloc

import numpy as np
from scipy import integrate, signal

srodowisko("numpy", "scipy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, scipy 1.18.1

List vs. array#

A list of float numbers is an array of pointers to separate objects, and every float object occupies \(24\) bytes of memory. A NumPy array of type float64 takes \(8\) bytes per number, with no pointers. Let us compare the memory and the time needed to square a million numbers.

lista = [0.1 * k for k in range(10**6)]
tablica = np.array(lista)
pamiec_listy = sys.getsizeof(lista) + sum(map(sys.getsizeof, lista))
print("lista:  ", pamiec_listy, "bajtów")
print("tablica:", tablica.nbytes, "bajtów + nagłówek",
      sys.getsizeof(tablica) - tablica.nbytes)


def te_same(a, b):
    """Czy dwa wyniki (listy albo tablice) są identyczne co do bitu?"""
    return np.array_equal(np.asarray(a), np.asarray(b))


czasy_kwadraty = porownaj({"lista składana": lambda: [v * v for v in lista],
                           "tablica NumPy": lambda: tablica * tablica},
                          zgodne=te_same)
lista:   32448728 bajtów
tablica: 8000000 bajtów + nagłówek 112
wariant              czas  przyspieszenie
lista składana    16.5 ms            1.0×
tablica NumPy      132 µs            125×

The array takes several times less memory, and it computes the squares tens to hundreds of times faster (the last column of the table). Moreover, the results are identical down to the bit: both programs perform the same multiplications of float64 numbers, only in a different loop.

Horner’s scheme on the whole grid#

In Lecture 5 (§5.1) we plotted the values of the polynomial \((x-1)^7\) computed by Horner’s scheme near its root, point by point: [p7(t) for t in ts]. The function horner uses only multiplication and addition, so it also works unchanged on an array: instead of a number \(t\) it receives an array of all the points at once. This is so-called duck typing. The function does not care about the type of its argument, only about whether it can be multiplied and added.

wsp7 = [1, -7, 21, -35, 35, -21, 7, -1]          # (x - 1)^7


def horner(wsp, t):
    s = 0
    for c in wsp:
        s = s * t + c
    return s


ts = np.linspace(0.99, 1.01, 100001)
ts_lista = ts.tolist()
def horner_punkt_po_punkcie():
    return np.array([horner(wsp7, t) for t in ts_lista])


czasy_horner = porownaj({"punkt po punkcie": horner_punkt_po_punkcie,
                         "horner(wsp7, tablica)": lambda: horner(wsp7, ts),
                         "np.polyval": lambda: np.polyval(wsp7, ts)},
                        zgodne=np.array_equal)
wariant                     czas  przyspieszenie
punkt po punkcie         18.0 ms            1.0×
horner(wsp7, tablica)     224 µs             81×
np.polyval                240 µs             75×

The same function called once on an array is several dozen times faster than a hundred thousand calls on numbers. The loop over the \(8\) coefficients stayed in Python, but the loop over the points moved to NumPy. The ready-made np.polyval computes with the same scheme and gives the same bits (zgodne=np.array_equal).

Quadrature#

In Lecture 5 (§5.4) the trapezoidal rule comes in two versions: with a generator inside sum and with an array (trapezy_wekt). Let us compare them, together with the ready-made function scipy.integrate.trapezoid, for \(\int_0^1 e^x\,dx\) and a million subintervals.

def trapezy(f, a, b, n):
    h = (b - a) / n
    return h * (f(a) / 2 + sum(f(a + i * h) for i in range(1, n)) + f(b) / 2)


def trapezy_wekt(f, a, b, n):
    ys = f(np.linspace(a, b, n + 1))
    return (b - a) / n * (ys.sum() - (ys[0] + ys[-1]) / 2)


def trapezy_scipy(f, a, b, n):
    xs = np.linspace(a, b, n + 1)
    return integrate.trapezoid(f(xs), xs)


n = 10**6
czasy_trapezy = porownaj({
    "generator i math.exp": lambda: trapezy(math.exp, 0, 1, n),
    "tablica i np.exp": lambda: trapezy_wekt(np.exp, 0, 1, n),
    "scipy.integrate.trapezoid": lambda: trapezy_scipy(np.exp, 0, 1, n)},
    zgodne=lambda a, b: abs(a - b) < 1e-12)
roznica = trapezy(math.exp, 0, 1, n) - trapezy_wekt(np.exp, 0, 1, n)
blad = trapezy_wekt(np.exp, 0, 1, n) - (math.e - 1)
print(f"różnica wersji: {roznica:.1e},  błąd metody: {blad:.4e},",
      f" wzór h²(e-1)/12: {(1 / n)**2 / 12 * (math.e - 1):.4e}")
wariant                         czas  przyspieszenie
generator i math.exp         43.2 ms            1.0×
tablica i np.exp             2.15 ms             20×
scipy.integrate.trapezoid    3.01 ms             14×
różnica wersji: 2.2e-16,  błąd metody: 1.4300e-13,  wzór h²(e-1)/12: 1.4319e-13

The array version is many times faster. The results differ only in the last digits, because the terms are summed in a different order. This difference is several orders of magnitude smaller than the error of the trapezoidal rule itself, which agrees with the formula \(h^2(e-1)/12\) from Lecture 5.

Newton basins: vectorizing over the starting points#

Newton’s method is sequential by nature: the step \(x_{k+1}\) depends on \(x_k\), so the steps cannot be performed all at once. In Lecture 5 (§5.2), however, we plotted the basins of attraction of the roots of \(z^3=1\), that is, the outcome of the method for every starting point of a grid. Different starting points are independent of one another. So we vectorize over the points: a single array of complex numbers holds all the points of the grid, and we perform each Newton step on the whole array at once.

PIERW = np.exp(2j * np.pi * np.arange(3) / 3)


def basen_punktu(z, iteracje=40):
    """Numer pierwiastka (0, 1, 2) albo 3, gdy metoda nie zbiega."""
    for _ in range(iteracje):
        if z == 0:
            return 3
        z = z - (z**3 - 1) / (3 * z**2)
    for k, r in enumerate(PIERW.tolist()):
        if abs(z - r) < 1e-6:
            return k
    return 3


def baseny_petla(n, iteracje=40):
    xs = np.linspace(-2, 2, n).tolist()
    return [[basen_punktu(complex(x, y), iteracje) for x in xs]
            for y in reversed(xs)]


def baseny_numpy(n, iteracje=40):
    xs = np.linspace(-2, 2, n)
    z = xs[None, :] + 1j * xs[::-1, None]
    with np.errstate(divide="ignore", invalid="ignore"):
        for _ in range(iteracje):
            z = z - (z**3 - 1) / (3 * z**2)
    odl = np.abs(z[..., None] - PIERW)
    return np.where(odl.min(axis=-1) < 1e-6, odl.argmin(axis=-1), 3)


czasy_baseny = porownaj({"punkt po punkcie": baseny_petla,
                         "cała siatka naraz": baseny_numpy}, 200,
                        zgodne=te_same)
wariant                 czas  przyspieszenie
punkt po punkcie      138 ms            1.0×
cała siatka naraz    8.72 ms             16×

Both versions assign the same root to each of the \(40{,}000\) points, and both perform \(40\) steps for every point. The array version is many times faster, because the loop over the points runs in C. This is a general rule: vectorize over independent tasks (points, samples, test cases), not over steps that depend on one another.

The Game of Life#

In Lab 8 a step of the Game of Life is computed by the function krok_zycia. For every cell it sums the eight neighbors, shifting the whole board with the function np.roll (the board is wrapped into a torus). Let us compare it with two other versions. The first is plain loops over the cells. The second is a convolution with the neighborhood mask, using the function scipy.signal.convolve2d.

def krok_zycia(P):
    """Krok gry w życie na planszy zwiniętej w torus (laboratorium 8)."""
    sasiedzi = sum(np.roll(np.roll(P, i, 0), j, 1)
                   for i in (-1, 0, 1) for j in (-1, 0, 1) if (i, j) != (0, 0))
    return ((sasiedzi == 3) | ((P == 1) & (sasiedzi == 2))).astype(np.uint8)


def krok_zycia_petle(P):
    n, m = len(P), len(P[0])
    nowa = [[0] * m for _ in range(n)]
    for w in range(n):
        for k in range(m):
            s = 0
            for i in (-1, 0, 1):
                for j in (-1, 0, 1):
                    if (i, j) != (0, 0):
                        s += P[(w + i) % n][(k + j) % m]
            nowa[w][k] = 1 if s == 3 or (P[w][k] == 1 and s == 2) else 0
    return nowa


MASKA = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]])


def krok_zycia_splot(P):
    s = signal.convolve2d(P, MASKA, mode="same", boundary="wrap")
    return ((s == 3) | ((P == 1) & (s == 2))).astype(np.uint8)


plansza = (np.random.default_rng(8).random((200, 200)) < 0.3).astype(np.uint8)
plansza_lista = plansza.tolist()
czasy_zycie = porownaj({
    "pętle po komórkach": lambda: krok_zycia_petle(plansza_lista),
    "np.roll (laboratorium 8)": lambda: krok_zycia(plansza),
    "scipy.signal.convolve2d": lambda: krok_zycia_splot(plansza)},
    zgodne=te_same)
wariant                        czas  przyspieszenie
pętle po komórkach          18.6 ms            1.0×
np.roll (laboratorium 8)    76.1 µs            245×
scipy.signal.convolve2d      616 µs             30×

Eight shifts of the whole board are more than a hundred times faster than the loops over the cells. Interestingly, they also beat SciPy’s ready-made convolution. The function convolve2d is general: it works for any mask and any numbers. Eight shifts and additions of arrays of type uint8 are simpler. A ready-made function is a good first choice, but not always the fastest one, and only a measurement can tell.

The Monte Carlo method#

In Lecture 5 we estimated the area of the lemniscate \((x^2+y^2)^2=2(x^2-y^2)\) by drawing random points in the rectangle \([-\sqrt2,\sqrt2]\times[-\tfrac12,\tfrac12]\) and counting the hits. The area is exactly \(2\). We compare drawing point by point with the random module against drawing a whole array at once with the generator np.random.default_rng. The two programs draw different numbers, so we compare the results with the exact value, not with each other.

S2 = math.sqrt(2)


def monte_carlo_petla(N):
    los, trafienia = random.Random(1), 0
    for _ in range(N):
        x, y = los.uniform(-S2, S2), los.uniform(-0.5, 0.5)
        trafienia += (x * x + y * y)**2 <= 2 * (x * x - y * y)
    return trafienia / N * 2 * S2


def monte_carlo_numpy(N):
    los = np.random.default_rng(1)
    x, y = los.uniform(-S2, S2, N), los.uniform(-0.5, 0.5, N)
    return float(((x * x + y * y)**2 <= 2 * (x * x - y * y)).mean() * 2 * S2)


czasy_mc = porownaj({"punkt po punkcie": monte_carlo_petla,
                     "tablica naraz": monte_carlo_numpy}, 10**6,
                    zgodne=lambda a, b: max(abs(a - 2), abs(b - 2)) < 0.01)
oszacowania = (monte_carlo_petla(10**6), monte_carlo_numpy(10**6))
p_traf = 2 / (2 * S2)
print("oszacowania:", oszacowania, " typowy błąd:",
      f"{2 * S2 * math.sqrt(p_traf * (1 - p_traf) / 10**6):.1e}")
wariant                czas  przyspieszenie
punkt po punkcie     170 ms            1.0×
tablica naraz       8.28 ms             21×
oszacowania: (2.0007558089402115, 2.0007133825333403)  typowy błąd: 1.3e-03

Drawing the whole array at once is many times faster. Both estimates have an error of order \(10^{-3}\), in line with the typical error of the Monte Carlo method for a million points.

Pitfalls#

NumPy speeds up operations on whole arrays. Outside this case it can slow a program down or silently change the result. Here are five pitfalls.

np.vectorize does not vectorize. The name is misleading: np.vectorize(f) creates a function that accepts arrays, but inside it calls f in a Python loop, element by element. The NumPy documentation says so explicitly: the function is provided for convenience, not for speed.

horner7 = np.vectorize(lambda t: horner(wsp7, t))
czasy_wektoryzuj = porownaj({
    "lista składana": horner_punkt_po_punkcie,
    "np.vectorize": lambda: horner7(ts),
    "prawdziwa wektoryzacja": lambda: horner(wsp7, ts)},
    zgodne=np.array_equal)
wariant                      czas  przyspieszenie
lista składana            18.3 ms            1.0×
np.vectorize              21.1 ms           0.87×
prawdziwa wektoryzacja     253 µs             72×

NumPy on single numbers. NumPy functions called on an ordinary number are slower than the functions from the math module, because every time they prepare an array computation: they check the type of the argument and create a result of type np.float64. In a loop over numbers (bisection, Newton’s method for a single point) it is better to use math. Similarly, np.sum(lista) pays for converting the list into an array at every call:

czasy_skalar = porownaj({"math.exp(0.7)": lambda: math.exp(0.7),
                         "np.exp(0.7)": lambda: np.exp(0.7)},
                        zgodne=lambda a, b: a == b)
czasy_konwersja = porownaj({"sum(lista)": lambda: sum(lista),
                            "np.sum(lista)": lambda: np.sum(lista),
                            "tablica.sum()": lambda: tablica.sum()},
                           zgodne=lambda a, b: abs(a - b) < 1e-3)
wariant             czas  przyspieszenie
math.exp(0.7)    40.4 ns            1.0×
np.exp(0.7)      76.6 ns           0.53×
wariant             czas  przyspieszenie
sum(lista)       1.35 ms            1.0×
np.sum(lista)    15.3 ms           0.09×
tablica.sum()     120 µs             11×

So we convert the data into an array once and then work on the array. np.sum called on a list is slower even than the plain sum.

Integer overflow. Python integers are unbounded. NumPy integer arrays have a fixed width, usually \(64\) bits, and on overflow they compute modulo \(2^{64}\), without a warning. An example from the instructor’s study, and the factorial from Lecture 1:

with np.errstate(over="raise"):       # nie pomoże: to nie są liczby float
    wyniki = {"sum([2**62, 2**62])": sum([2**62, 2**62]),
              "np.array([2**62, 2**62]).sum()": np.array([2**62, 2**62]).sum(),
              "math.factorial(25)": math.factorial(25),
              "np.prod(np.arange(1, 26))": np.prod(np.arange(1, 26))}
for opis, wartosc in wyniki.items():
    print(f"{opis:30} = {wartosc}")
sum([2**62, 2**62])            = 9223372036854775808
np.array([2**62, 2**62]).sum() = -9223372036854775808
math.factorial(25)             = 15511210043330985984000000
np.prod(np.arange(1, 26))      = 7034535277573963776

The product of the numbers from \(1\) to \(25\) in NumPy is simply wrong, and nothing signals it. The setting np.errstate(over="raise") controls only floating-point errors. It does not detect integer overflow in NumPy arrays. For integers that may exceed \(2^{63}\) we stay with Python integers, or we use arrays of type object, which store Python integers but lose NumPy’s speed.

Memory in broadcasting. Broadcasting x[:, None] - x[None, :] creates an array of all \(n^2\) differences. Let us compute the sum of all pairwise distances \(\sum_{i<j}|x_i-x_j|\) for \(n=3000\) points in three ways: with the whole matrix of differences, in blocks of \(256\) rows, as in the instructor’s study, and with a formula. If \(y_0\le y_1\le\dots\le y_{n-1}\) are the same numbers after sorting, then \(y_k\) is greater than \(k\) of the numbers and smaller than \(n-1-k\) of them, so

\[ \sum_{i<j}|x_i-x_j|=\sum_{k=0}^{n-1}\bigl(2k-(n-1)\bigr)\,y_k . \]
def odleglosci_macierz(x):
    return float(np.abs(x[:, None] - x[None, :]).sum() / 2)


def odleglosci_blokami(x, b=256):
    s = 0.0
    for i in range(0, len(x), b):
        s += np.abs(x[i:i + b, None] - x[None, :]).sum()
    return float(s / 2)


def odleglosci_wzor(x):
    y = np.sort(x)
    return float(np.dot(y, 2 * np.arange(len(y)) - (len(y) - 1)))


def szczyt_pamieci(f, *args):
    tracemalloc.start()
    f(*args)
    szczyt = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return szczyt


x = np.random.default_rng(7).random(3000)
ODLEGLOSCI = {"macierz różnic": odleglosci_macierz,
              "bloki po 256 wierszy": odleglosci_blokami,
              "wzór po posortowaniu": odleglosci_wzor}
czasy_pary = porownaj(ODLEGLOSCI, x,
                      zgodne=lambda a, b: abs(a - b) < 1e-9 * abs(b))
pamiec_pary = {f.__name__: szczyt_pamieci(f, x) for f in ODLEGLOSCI.values()}
for nazwa, bajty in pamiec_pary.items():
    print(f"{nazwa:20} szczyt pamięci: {bajty / 2**20:7.2f} MiB")
wariant                    czas  przyspieszenie
macierz różnic          4.61 ms            1.0×
bloki po 256 wierszy    3.04 ms            1.5×
wzór po posortowaniu    58.7 µs             78×
odleglosci_macierz   szczyt pamięci:  137.33 MiB
odleglosci_blokami   szczyt pamięci:   11.72 MiB
odleglosci_wzor      szczyt pamięci:    0.07 MiB

The peak memory of the matrix of differences for \(n=3000\) exceeds a hundred megabytes, and for \(n=10^5\) the matrix would already need \(8\cdot10^{10}\) bytes, that is, \(80\) GB. Blocks limit the memory to \(8bn\) bytes, but they still perform \(n^2\) subtractions. The formula after sorting needs \(O(n\log n)\) operations and takes almost no memory. Once again mathematics wins, just as in part 2.

Summary#

Let us collect the speedups obtained in this part. Each time we replaced a loop in Python with an operation on a whole array.

zestawienie = {
    "kwadraty miliona liczb": czasy_kwadraty,
    "Horner, 10⁵ punktów": czasy_horner,
    "trapezy, n = 10⁶": czasy_trapezy,
    "baseny Newtona 200×200": czasy_baseny,
    "gra w życie 200×200": czasy_zycie,
    "Monte Carlo, 10⁶ punktów": czasy_mc,
}
przyspieszenia = {nazwa: list(t.values())[0] / min(t.values())
                  for nazwa, t in zestawienie.items()}
for nazwa, r in przyspieszenia.items():
    print(f"{nazwa:26} najszybsza wersja tablicowa: {krotnosc(r):>6}")

fig, ax = plt.subplots(figsize=(8, 3.2))
nazwy = list(przyspieszenia)[::-1]
wartosci = [przyspieszenia[k] for k in nazwy]
ax.scatter(wartosci, range(len(nazwy)), s=70, color=INDYGO,
           edgecolors="white", linewidths=2, zorder=3)
for i, v in enumerate(wartosci):
    ax.annotate(krotnosc(v), (v, i), xytext=(9, 0), textcoords="offset points",
                va="center", fontsize=9, color=TUSZ)
ax.set_yticks(range(len(nazwy)), nazwy)
ax.set_xscale("log")
ax.set_xlim(1, max(przyspieszenia.values()) * 6)
ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g}×"))
ax.xaxis.set_minor_formatter(NullFormatter())
ax.axvline(1, color=SZARY, lw=1)
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("Ile razy szybciej z tablicami NumPy", loc="left", fontsize=11)
plt.tight_layout()
plt.show()
kwadraty miliona liczb     najszybsza wersja tablicowa:   125×
Horner, 10⁵ punktów        najszybsza wersja tablicowa:    81×
trapezy, n = 10⁶           najszybsza wersja tablicowa:    20×
baseny Newtona 200×200     najszybsza wersja tablicowa:    16×
gra w życie 200×200        najszybsza wersja tablicowa:   245×
Monte Carlo, 10⁶ punktów   najszybsza wersja tablicowa:    21×
../_images/92536d669a84d2d2082b2a04b96a2abd5814d289bad8dcf3ce2539e2b90883a6.png
  • A NumPy array stores numbers of a single type next to one another, and operations on whole arrays are carried out by loops in C. The speedup is usually from a dozen or so to a few hundred times.

  • Vectorize over independent tasks: grid points, samples, cells of the board. Steps that depend on one another (the Newton iteration for a single point) cannot be performed all at once.

  • Often it is enough to call the same function on an array (duck typing), as with horner.

  • Pitfalls: np.vectorize is a loop, NumPy functions on single numbers are slower than math, converting a list into an array has a cost, integers overflow without a warning, and broadcasting can take \(n^2\) memory.

Exercises#

  1. ★ Write an array version of the function srodki(f, a, b, n) (the midpoint rule) and compare it with the generator version for \(n=10^6\).

  2. ★ Compute \(\sum_{k=1}^{n}k^2\) in NumPy for \(n=3\cdot10^6\) on the array np.arange(1, n + 1) and compare it with the formula \(n(n+1)(2n+1)/6\) in Python integers. Explain the difference. Fix the NumPy version by choosing a suitable array type.

  3. ★★ For the Game of Life, measure the time of \(100\) steps on a \(500\times500\) board with the np.roll version and with the loops (for the loops, measure one step and estimate). How many steps per second does each version give?

  4. ★★ Prove the formula for \(\sum_{i<j}|x_i-x_j|\) in terms of the sorted values. How many operations does the version with sorting perform, and how many the matrix of differences?