Part 9. Compilation and parallel computing#
The ladder of laziness from part 8 ends with two rungs that we reach for only
at the very end. Compilation turns a Python loop into the processor’s machine code.
Parallel computing divides the work among several processor cores. Both rungs come at
a price. Compilation takes time, and it works only for numbers and arrays, not for arbitrary
Python objects. Parallel computing requires starting additional threads or processes and dividing
up the work, and the speedup is at most the number of cores. We use the Numba compiler and the
concurrent.futures module from the standard library. The examples are familiar: the double loop
from part 1, the Collatz steps from Lecture 1, Lab 8, and
part 2, Gaussian elimination from Lecture 6 and part 6,
and the summation of float numbers from Lecture 1 and part 4.
import math
import multiprocessing
import os
import pathlib
import platform
import subprocess
import sys
import tempfile
import textwrap
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from fractions import Fraction
import numba
import numpy as np
from numba import njit, prange
from numba.core.errors import TypingError
srodowisko("numpy", "numba")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, numba 0.68.1
Parallel computing depends on how many cores the processor has. Apple computers have two kinds of
cores: performance cores and slower efficiency cores. We read this off with the system command
sysctl.
def sysctl(klucz):
"""Parametr systemu macOS jako napis (pusty, gdy go nie ma)."""
if sys.platform != "darwin":
return ""
wynik = subprocess.run(["sysctl", "-n", klucz], capture_output=True,
text=True)
return wynik.stdout.strip()
wydajne = sysctl("hw.perflevel0.physicalcpu")
energooszczedne = sysctl("hw.perflevel1.physicalcpu")
print("rdzenie procesora:", os.cpu_count())
if wydajne and energooszczedne:
print(f" w tym wydajne: {wydajne}, energooszczędne: {energooszczedne}")
print("wątki, których domyślnie używa Numba:", numba.get_num_threads())
rdzenie procesora: 10
w tym wydajne: 4, energooszczędne: 6
wątki, których domyślnie używa Numba: 10
Numba: just-in-time compilation#
The CPython interpreter executes bytecode instruction by instruction and checks the types of the
objects at every operation (part 1). Numba works differently. On the first call
of a function, it reads the types of the arguments, for example int64, and translates the whole
function into the processor’s machine code using LLVM, the library on which, for example, the
clang compiler is also built. Such compilation at the moment of first use is called
just-in-time (JIT) compilation. The njit decorator (from no Python) requires the function to
use only numbers, NumPy arrays, tuples, and a few simple data structures, but not Python objects.
Let us compile the first program from part 1.
def suma_petla(n):
s = 0
for i in range(n):
for j in range(n):
s += i + j
return s
suma_petla_jit = njit(suma_petla) # ta sama funkcja, skompilowana
start = time.perf_counter()
wynik = suma_petla_jit(100) # kompilacja i obliczenie
t_pierwsze = time.perf_counter() - start
start = time.perf_counter()
suma_petla_jit(100) # samo obliczenie
t_drugie = time.perf_counter() - start
print(f"wynik: {wynik}")
print(f"pierwsze wywołanie: {czas(t_pierwsze)}, drugie: {czas(t_drugie)}")
print("skompilowane wersje:", suma_petla_jit.signatures)
wynik: 990000
pierwsze wywołanie: 377 ms, drugie: 19.1 µs
skompilowane wersje: [(int64,)]
The first call includes the compilation and takes thousands of times longer than the second. The
signatures list shows for which argument types the function has already been compiled: here, for
a single integer of type int64. A call with an argument of a different type, for example
float, would trigger the compilation of a second version. The zmierz function from part 1
calls the measured function once before measuring, so the compilation time does not appear in the
tables of this part. Compilation pays off only when the function computes for a long time or is
called many times.
How does the time grow with \(n\)? We measure the Python version for \(n\le1000\) and the compiled one all the way up to \(n=10^6\), that is, up to \(10^{12}\) iterations of the inner loop. We compare every result with the formula \(S(n)=n^2(n-1)\) from part 1.
print(f"{'n':>9} {'Python':>9} {'Numba':>9}")
czasy_jit = {}
for n in [10**2, 10**3, 10**4, 10**5, 10**6]:
assert suma_petla_jit(n) == n**2 * (n - 1)
czasy_jit[n] = zmierz(suma_petla_jit, n)
t_python = czas(zmierz(suma_petla, n)) if n <= 1000 else "—"
print(f"{n:>9} {t_python:>9} {czas(czasy_jit[n]):>9}")
n Python Numba
100 120 µs 49.8 ns
1000 18.4 ms 51.0 ns
10000 — 51.7 ns
100000 — 53.0 ns
1000000 — 52.8 ns
The time of the Python version grows like \(n^2\): an \(n\) ten times larger means a computation one hundred times longer. The time of the compiled function does not depend on \(n\) at all, and for \(n=10^6\) it is shorter than a microsecond. Yet a trillion additions would take a hundred seconds even at ten billion additions per second. So the compiler must have found a shortcut. Here is the machine code it generated (we omit the wrapper that converts Python objects into machine numbers):
asm = suma_petla_jit.inspect_asm(suma_petla_jit.signatures[0])
rozkazy = []
for wiersz in asm.split("cpython")[0].splitlines():
if wiersz.startswith("\t") and not wiersz.strip().startswith("."):
rozkazy.append(" ".join(wiersz.split())) # rozkaz procesora
elif wiersz.startswith(("LBB", ".LBB")):
rozkazy.append(wiersz) # etykieta skoku
print(f"procesor: {platform.machine()}, rozkazów: "
f"{sum(not r.endswith(':') for r in rozkazy)}")
print("\n".join(rozkazy))
procesor: arm64, rozkazów: 18
subs x8, x2, #1
b.lt LBB0_2
sub x9, x2, #2
mul x10, x8, x9
umulh x9, x8, x9
extr x9, x9, x10, #1
add x10, x9, x2, lsl #1
sub x10, x10, #1
madd x9, x9, x2, x9
add x9, x8, x9
madd x8, x10, x8, x9
str x8, [x0]
mov w0, #0
ret
LBB0_2:
mov x8, #0
str x8, [x0]
mov w0, #0
ret
This is the entire code of the function: a dozen or so instructions for the arm64 processor on
which this page was built (on a different processor the instructions look different). There is no
loop in it. The only conditional branch (b.lt) handles the case \(n\le0\), in which the result is
\(0\). The rest is a few multiplications (mul, umulh, madd) and additions. The LLVM optimizer
recognized that the loops sum arithmetic progressions and replaced them with a formula, the same
\(n^2(n-1)\) that we derived ourselves in part 1. The compiler is lazy too. Two things follow
from this. First, the compiler will sometimes turn a simple loop into a formula on its own.
Second, when measuring compiled code, you also have to check that the compiler has not removed
precisely the work you wanted to measure.
A loop that cannot be vectorized: Collatz steps#
In part 5 we moved loops into NumPy. The Collatz steps are not suited to this: each number needs a different number of steps, and the next step depends on the previous one. NumPy would have to carry all the trajectories along at once until the longest one ends. A loop compiled by Numba computes exactly as many steps for each number as needed.
We compare four versions: each number separately and with a table of known results, in Python and
in Numba. The table of known results is a simpler variant of the dictionary-based memoization from
part 2. We go through the numbers in order and follow the trajectory of the number start only up
to the first number smaller than start. By then we already know the number of steps for that
number. Nobody knows whether every trajectory eventually drops below its starting point: this
statement is equivalent to the Collatz conjecture. For the numbers checked here, the computation
terminates, so for them it is true.
def kroki(n):
k = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
k += 1
return k
def kroki_wszystkie(N):
return np.array([kroki(n) for n in range(1, N + 1)])
def kroki_tablica(N):
"""Kroki dla n ≤ N; trajektorię liczby start śledzimy tylko do
pierwszej liczby mniejszej od start, bo jej wynik już znamy."""
znane = np.zeros(N + 1, dtype=np.int64)
for start in range(2, N + 1):
n, k = start, 0
while n >= start:
n = n // 2 if n % 2 == 0 else 3 * n + 1
k += 1
znane[start] = k + znane[n]
return znane[1:]
kroki_jit = njit(kroki)
kroki_tablica_jit = njit(kroki_tablica)
@njit
def kroki_wszystkie_jit(N):
wynik = np.empty(N, dtype=np.int64)
for n in range(1, N + 1):
wynik[n - 1] = kroki_jit(n)
return wynik
def te_same(a, b):
return np.array_equal(np.asarray(a), np.asarray(b))
N = 10**5
czasy_collatz = porownaj({
"Python: każda liczba osobno": kroki_wszystkie,
"Python: tablica znanych wyników": kroki_tablica,
"Numba: każda liczba osobno": kroki_wszystkie_jit,
"Numba: tablica znanych wyników": kroki_tablica_jit}, N, zgodne=te_same)
wariant czas przyspieszenie
Python: każda liczba osobno 332 ms 1.0×
Python: tablica znanych wyników 25.6 ms 13×
Numba: każda liczba osobno 8.44 ms 39×
Numba: tablica znanych wyników 363 µs 916×
Compilation speeds up the same program tens of times, and the table of known results gives a several-fold speedup in both Python and Numba. The two rungs of the ladder act independently, so their gains multiply: together they give a speedup on the order of a thousand times. Such a fast program lets us reach further. Let us find the number \(n\le10^7\) with the longest trajectory.
N = 10**7
start = time.perf_counter()
kroki_do_N = kroki_tablica_jit(N)
t_N = time.perf_counter() - start
rekord = int(np.argmax(kroki_do_N))
print(f"n ≤ {N}: najwięcej kroków ({kroki_do_N[rekord]}) ma n = {rekord + 1}")
print(f"czas: {czas(t_N)}")
t_python = 100 * czasy_collatz["Python: każda liczba osobno"]
print(f"Python, każda liczba osobno: ponad {czas(t_python)} (szacunek)")
n ≤ 10000000: najwięcej kroków (685) ma n = 8400511
czas: 49.2 ms
Python, każda liczba osobno: ponad 33.2 s (szacunek)
Numba finds the record for \(n\le10^7\) in a fraction of a second. The Python version, number by number, would need more than a hundred times as much time as in the table for \(N=10^5\): there are a hundred times as many numbers, and their trajectories are longer on average.
Numba computes with 64-bit integers, not with Python’s unbounded integers. So let us check that
the trajectories do not leave the range of the type int64. Here, too, it is enough to go up to
the first number smaller than the starting number, because we checked the rest of the trajectory
earlier. We compare each new number with the maximum before we compute the next one from it, and
the starting numbers are small. So if the maximum is smaller than \((2^{63}-1)/3\), then no
operation \(3n+1\) has left the range.
@njit
def najwieksza_liczba(N):
"""Największa liczba na trajektoriach liczb n ≤ N."""
m = 1
for start in range(2, N + 1):
n = start
while n >= start:
n = n // 2 if n % 2 == 0 else 3 * n + 1
m = max(m, n)
return m
m = najwieksza_liczba(N)
granica = np.iinfo(np.int64).max // 3
print(f"największa liczba na trajektoriach n ≤ {N}: {m} ≈ {m:.1e}")
print(f"(2⁶³ - 1) / 3 ≈ {granica:.1e}, zapas: {granica / m:.0f} razy")
największa liczba na trajektoriach n ≤ 10000000: 60342610919632 ≈ 6.0e+13
(2⁶³ - 1) / 3 ≈ 3.1e+18, zapas: 50950 razy
Compilation will not replace a library: Gaussian elimination#
In part 6, Gaussian elimination from Lecture 6 in pure Python lost to the function
np.linalg.solve (the LAPACK library) by a factor of hundreds. Will compilation even the odds?
Numba does not compile lists of lists, so we write the same algorithm on a NumPy array, with
explicit loops.
def eliminacja(A, b):
"""Eliminacja Gaussa z częściowym wyborem elementu głównego (wykład 6)."""
n = len(A)
M = [list(w) + [bi] for w, bi in zip(A, b)]
for k in range(n):
p = max(range(k, n), key=lambda i: abs(M[i][k]))
M[k], M[p] = M[p], M[k]
for i in range(k + 1, n):
m = M[i][k] / M[k][k]
M[i] = [a - m * c for a, c in zip(M[i], M[k])]
x = [0] * n
for i in reversed(range(n)):
s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))
x[i] = s / M[i][i]
return x
@njit
def eliminacja_jit(A, b):
"""Ten sam algorytm na tablicy NumPy, z jawnymi pętlami."""
n = len(A)
M = np.empty((n, n + 1))
M[:, :n] = A
M[:, n] = b
for k in range(n):
p = k + np.argmax(np.abs(M[k:, k])) # element główny
for j in range(n + 1):
M[k, j], M[p, j] = M[p, j], M[k, j]
for i in range(k + 1, n):
m = M[i, k] / M[k, k]
for j in range(k, n + 1):
M[i, j] -= m * M[k, j]
x = np.zeros(n)
for i in range(n - 1, -1, -1):
s = 0.0
for j in range(i + 1, n):
s += M[i, j] * x[j]
x[i] = (M[i, n] - s) / M[i, i]
return x
los = np.random.default_rng(2026)
rozmiary = [50, 100, 200, 400, 800]
czasy_gauss = {"eliminacja w Pythonie (część 6)": [],
"ta sama eliminacja w Numbie": [],
"np.linalg.solve (LAPACK)": []}
print(f"{'n':>4} {'Python':>9} {'Numba':>9} {'LAPACK':>9}"
f" {'Numba / LAPACK':>14}")
for n in rozmiary:
A = los.integers(-9, 10, (n, n)).astype(float)
b = los.integers(-9, 10, n).astype(float)
x = np.linalg.solve(A, b)
assert np.allclose(eliminacja_jit(A, b), x)
t_py = math.nan # Python tylko do n = 200
if n <= 200:
assert np.allclose(eliminacja(A.tolist(), b.tolist()), x)
t_py = zmierz(eliminacja, A.tolist(), b.tolist())
t_nb = zmierz(eliminacja_jit, A, b)
t_la = zmierz(np.linalg.solve, A, b)
for nazwa, t in zip(czasy_gauss, (t_py, t_nb, t_la)):
czasy_gauss[nazwa].append(t)
t_py = czas(t_py) if n <= 200 else "—"
print(f"{n:>4} {t_py:>9} {czas(t_nb):>9} {czas(t_la):>9}"
f" {krotnosc(t_nb / t_la):>14}")
wykres_skalowania(rozmiary, czasy_gauss, "Rozwiązanie układu n × n")
n Python Numba LAPACK Numba / LAPACK
50 1.33 ms 19.3 µs 14.5 µs 1.3×
100 10.4 ms 123 µs 44.7 µs 2.8×
200 85.2 ms 917 µs 138 µs 6.7×
400 — 6.95 ms 608 µs 11×
800 — 52.7 ms 2.68 ms 20×
Numba speeds up the elimination by a factor on the order of a hundred, but LAPACK remains faster,
and its advantage grows with \(n\). For large systems it is several-fold. Compilation removes the
cost of the interpreter, but it does not change the algorithm. For each \(k\), our loop passes over
the whole remaining part of the matrix and spends more time reading from memory than computing.
LAPACK divides the matrix into blocks that fit in the CPU cache and performs most of the work as
matrix multiplication (BLAS) with vector instructions, and it can also use several cores. This is
the result of decades of work by specialists, and the njit decorator will not replace it. The
instructor’s study shows the same thing: there, single-threaded BLAS was faster than C code
running on four cores.
Pitfalls of compilation#
Integers have 64 bits#
In Python, integers are unbounded. In Numba, as in NumPy (part 5), they have 64 bits.
@njit
def silnia(n):
w = 1
for k in range(2, n + 1):
w *= k
return w
for n in (20, 21, 25):
print(f"{n}! Numba: {silnia(n):>20} Python: {math.factorial(n)}")
20! Numba: 2432902008176640000 Python: 2432902008176640000
21! Numba: -4249290049419214848 Python: 51090942171709440000
25! Numba: 7034535277573963776 Python: 15511210043330985984000000
The number \(20!\) fits in the range of the type int64 (up to \(2^{63}-1\approx9.2\cdot10^{18}\)),
but \(21!\) no longer does. The result silently “wraps around” and comes out negative, and \(25!\) is
positive but wrong. That is why, when compiling, we keep an eye on the range, as with the Collatz
steps. Exact computations with large numbers (factorials, the binomial coefficients from part 2)
stay in Python.
The same loop gives the same result, unless we allow changes#
Let us sum a million copies of the number 0.1, as in part 4. We compare the loop in Python, the
same loop compiled by Numba, the same loop with the option fastmath=True, and the function
np.sum. The results differ in the last digits, so in the contract we allow a relative difference
of \(10^{-9}\).
def suma_po_kolei(x):
s = 0.0
for i in range(len(x)):
s += x[i]
return s
suma_jit = njit(suma_po_kolei)
suma_jit_fastmath = njit(fastmath=True)(suma_po_kolei)
x = np.full(10**6, 0.1)
sumy = {"pętla w Pythonie": suma_po_kolei,
"ta sama pętla w Numbie": suma_jit,
"Numba, fastmath=True": suma_jit_fastmath,
"np.sum": np.sum}
czasy_sumy = porownaj(sumy, x, zgodne=lambda a, b: math.isclose(
a, b, rel_tol=1e-9))
print()
for nazwa, f in {**sumy, "math.fsum": math.fsum}.items():
print(f"{nazwa:>24}: {float(f(x))!r}")
wariant czas przyspieszenie
pętla w Pythonie 49.8 ms 1.0×
ta sama pętla w Numbie 539 µs 93×
Numba, fastmath=True 80.2 µs 621×
np.sum 118 µs 422×
pętla w Pythonie: 100000.00000133288
ta sama pętla w Numbie: 100000.00000133288
Numba, fastmath=True: 100000.00000022355
np.sum: 100000.00000000003
math.fsum: 100000.0
By default, Numba preserves the order of operations from the code and the rules of the IEEE 754
standard, so the compiled loop gives a result that is bit-for-bit identical to that of the Python
loop, with the same rounding error. The option fastmath=True allows the compiler to change the
order of the additions. The compiler then accumulates several partial sums at once with vector
instructions. This is several times faster, but the result is different. Here it happens to be
more accurate, but the compiler promises nothing of the kind. With fastmath it also assumes,
for example, that the data contain no nan and no infinities. The function np.sum uses
pairwise summation, which usually gives a smaller error than adding the numbers one after
another. The correctly rounded sum, \(100000.0\), is given by math.fsum. The
IEEE 754 deep dive says more about the order of operations on
floating-point numbers.
Only numbers and arrays#
@njit
def harmoniczna(n):
s = Fraction(0)
for k in range(1, n + 1):
s += Fraction(1, k)
return s
try:
harmoniczna(10)
except TypingError as blad:
opis = next(w for w in str(blad).splitlines() if "Fraction" in w)
print("TypingError:")
print(textwrap.fill(opis, width=79))
TypingError:
Untyped global name 'Fraction': Cannot determine Numba type of <class
'abc.ABCMeta'>
The compiler must know the type of every variable and be able to convert it into a machine type.
It does not know the Fraction class, Python’s big integers, or SymPy expressions, and it will not
call functions from SciPy or SymPy either. So the exact computations from Lectures 3 and 6 and the
harmonic numbers from part 7 stay in Python. That does no harm, because there
the time goes into the arithmetic on large numbers itself, not into the interpreter. We pass NumPy
arrays to compiled functions, not Python lists: Numba accepts lists only with a warning that this
feature will be removed.
Parallel computing#
An ordinary Python program computes on a single core. The work can be divided up in three ways.
Threads (the
threadingmodule, theThreadPoolExecutorclass) share the program’s memory. In standard CPython, however, the global interpreter lock (GIL) allows only one thread at a time to execute Python code.Processes (the
multiprocessingmodule, theProcessPoolExecutorclass) are separate programs, each with its own interpreter and its own lock. They compute truly in parallel, but each one has to be started, and the tasks and results have to be sent between the processes.Compiled code does not need the interpreter, so it does not need the lock either. Numba distributes the iterations of a
prangeloop among threads.
Threads and processes in pure Python#
Child processes must know the function they are to execute. On macOS and Windows, a new process
starts from scratch (the spawn method) and does not see functions defined in notebook cells, so
the function has to be placed in a module. In your own program, an ordinary .py file next to the
notebook is enough. Here, to keep the notebook self-contained, we write the module to a temporary
directory. We choose the spawn method explicitly so that the program behaves the same way on
every system.
MODUL = '''\
def kroki(n):
k = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
k += 1
return k
def kroki_przedzialu(a, b):
"""Liczby kroków Collatza dla n = a, a + 1, ..., b - 1."""
return [kroki(n) for n in range(a, b)]
'''
katalog = pathlib.Path(tempfile.mkdtemp())
(katalog / "collatz_zadania.py").write_text(MODUL)
sys.path.insert(0, str(katalog)) # procesy potomne dostaną tę ścieżkę
import collatz_zadania
def przedzialy(N, czesci):
"""Dzieli 1, ..., N na kolejne przedziały [a, b)."""
g = [1 + N * k // czesci for k in range(czesci + 1)]
return list(zip(g, g[1:]))
def w_puli(pula, N, czesci):
"""Kroki dla n ≤ N policzone w puli wątków albo procesów."""
poczatki, konce = zip(*przedzialy(N, czesci))
wynik = []
for kawalek in pula.map(collatz_zadania.kroki_przedzialu, poczatki,
konce):
wynik += kawalek
return np.array(wynik)
spawn = multiprocessing.get_context("spawn")
watki = ThreadPoolExecutor(max_workers=4)
start = time.perf_counter()
procesy = ProcessPoolExecutor(max_workers=4, mp_context=spawn)
w_puli(procesy, 100, 4) # uruchomienie procesów
t_start = time.perf_counter() - start
print("uruchomienie puli czterech procesów:", czas(t_start))
N = 10**5
czasy_pule = porownaj({"jeden proces": lambda: kroki_wszystkie(N),
"4 wątki": lambda: w_puli(watki, N, 16),
"4 procesy": lambda: w_puli(procesy, N, 16)},
zgodne=te_same)
watki.shutdown()
procesy.shutdown()
uruchomienie puli czterech procesów: 44.8 ms
wariant czas przyspieszenie
jeden proces 341 ms 1.0×
4 wątki 338 ms 1.0×
4 procesy 115 ms 3.0×
Four threads give no speedup at all: the lock passes from thread to thread, so at any moment only
one of them is computing. Four processes give a clear speedup, though less than fourfold. The
tasks and results have to be serialized into bytes (the pickle module) and sent between the
processes, and in the meantime the processor also serves other programs. We divided the work into
sixteen tasks, four per process, so that the cores that finish early have something to do.
The process pool also has to be started, which takes time (the first line above). For a small task, a new pool loses to a single process:
def nowa_pula(N):
with ProcessPoolExecutor(max_workers=4, mp_context=spawn) as pula:
return w_puli(pula, N, 16)
czasy_male = porownaj({"jeden proces": lambda: kroki_wszystkie(1000),
"nowa pula czterech procesów": lambda: nowa_pula(1000)},
zgodne=te_same)
wariant czas przyspieszenie
jeden proces 1.98 ms 1.0×
nowa pula czterech procesów 42.1 ms 0.05×
So we create a process pool once and give it large chunks of work. It pays off only when the work of a single process takes much longer than starting it up and transferring the data.
Numba: threads without the lock#
It is enough to replace range with prange and add the option parallel=True, and Numba will
distribute the iterations of the loop among threads. This is allowed because the iterations are
independent: each one writes a different element of the array wynik.
@njit(parallel=True)
def kroki_rownolegle(N):
wynik = np.empty(N, dtype=np.int64)
for i in prange(N): # obroty pętli dzielone między wątki
wynik[i] = kroki_jit(i + 1)
return wynik
N = 10**5
czasy_prange = porownaj({
"Numba: każda liczba osobno": kroki_wszystkie_jit,
"Numba: prange": kroki_rownolegle,
"Numba: tablica znanych wyników": kroki_tablica_jit}, N, zgodne=te_same)
wariant czas przyspieszenie
Numba: każda liczba osobno 8.48 ms 1.0×
Numba: prange 1.78 ms 4.8×
Numba: tablica znanych wyników 363 µs 23×
The prange loop gives a speedup of several times. Still, the version with the table of known
results on a single core is faster than the parallel version on all cores. A better algorithm
beats more cores. That version cannot easily be parallelized, because each step uses the
results of the previous ones.
How much additional cores help#
Let us measure how the time depends on the number \(k\) of processes (pure Python, \(N=10^5\)) and of Numba threads (\(N=10^6\), so that the work of a single thread takes about as long). The speedup is \(S_k=T_1/T_k\), where \(T_k\) is the time on \(k\) cores. Ideally, \(S_k=k\).
liczby = [k for k in (1, 2, 4, 6, 8, 10, 12, 16) if k <= os.cpu_count()]
czasy_procesow, czasy_watkow = [], []
for k in liczby:
with ProcessPoolExecutor(max_workers=k, mp_context=spawn) as pula:
w_puli(pula, 1000, k) # uruchomienie procesów
czasy_procesow.append(zmierz(w_puli, pula, 10**5, 4 * k))
numba.set_num_threads(k)
czasy_watkow.append(zmierz(kroki_rownolegle, 10**6))
numba.set_num_threads(numba.config.NUMBA_NUM_THREADS)
print(f"{'k':>3} {'procesy':>9} {'S_k':>6} {'wątki Numby':>11} {'S_k':>6}")
for k, tp, tw in zip(liczby, czasy_procesow, czasy_watkow):
print(f"{k:>3} {czas(tp):>9} {krotnosc(czasy_procesow[0] / tp):>6}"
f" {czas(tw):>11} {krotnosc(czasy_watkow[0] / tw):>6}")
wykres_przyspieszenia(
liczby, {"procesy, czysty Python, N = 10⁵": czasy_procesow,
"wątki Numby (prange), N = 10⁶": czasy_watkow},
"Kroki Collatza: przyspieszenie na k rdzeniach",
int(wydajne) if wydajne else None)
k procesy S_k wątki Numby S_k
1 340 ms 1.0× 105 ms 1.0×
2 189 ms 1.8× 55.9 ms 1.9×
4 119 ms 2.9× 30.1 ms 3.5×
6 104 ms 3.3× 24.0 ms 4.4×
8 83.7 ms 4.1× 21.9 ms 4.8×
10 78.5 ms 4.3× 18.0 ms 5.8×
The speedup grows with the number of processes and threads, but more slowly than in the ideal case, and with all cores in use it is clearly smaller than their number. There are several reasons for this. The cores are not all alike: on the computer on which this page was built, only some of them are performance cores, and the additional tasks land on the slower efficiency cores. On top of that come the costs of dividing up the work, the memory shared by all cores, and other programs running at the same time. That is why the plot looks a little different every time the page is built.
Almost every program has a part that must be executed sequentially: reading the data, dividing up the work, collecting the results. If it takes a fraction \(f\) of the time on a single core, then on \(k\) cores
This is Amdahl’s law (G. Amdahl, 1967). With \(f=5\%\), no number of cores will speed the program up more than \(20\) times. The conclusions are the same as along the whole ladder: first we reduce the work (mathematics, algorithm), then we speed up each of its steps (library, vectorization, compilation), and only at the very end do we divide it among cores.
What else to keep in mind#
Libraries already compute in parallel. The
@operator and the functionnp.linalg.solvecall the BLAS and LAPACK libraries, which can themselves use several cores. A pool of processes, each of which runs a multithreaded BLAS, creates more threads than there are cores, and then the threads take time away from one another. The number of BLAS threads is limited with environment variables set before NumPy is imported (for exampleOMP_NUM_THREADSorOPENBLAS_NUM_THREADS, depending on the library) or with thethreadpoolctlpackage.Shared data means race conditions. When two threads modify the same element of an array, for example
h[k] += 1in aprangeloop, the result depends on which one gets there first (a race condition), and it is wrong. Numba recognizes a sums += …in aprangeloop as a reduction and computes it correctly. It is safest when each iteration of the loop writes its own element of the result, as inkroki_rownolegle.Python without the lock. Since version 3.13 there has been a separate build of the CPython interpreter without the GIL (PEP 703; experimental in version 3.13, officially supported since 3.14, but not the default). In it, threads execute Python code in parallel, and it is up to the programmer to ensure correct access to shared data.
Other compilers. Cython translates Python with type declarations into C. Functions written in C can be called from Python through the
ctypesmodule (we compiled C programs in the IEEE 754 deep dive). The JAX, PyTorch, and CuPy libraries can compute on graphics cards.
Summary: Collatz steps from Python to Numba#
Let us collect the times of all the versions of computing the Collatz steps for \(n\le10^5\) from this part.
podsumowanie = {
"Python": czasy_collatz["Python: każda liczba osobno"],
"Python, 4 wątki": czasy_pule["4 wątki"],
"Python, 4 procesy": czasy_pule["4 procesy"],
"Python, tablica znanych wyników":
czasy_collatz["Python: tablica znanych wyników"],
"Numba": czasy_collatz["Numba: każda liczba osobno"],
"Numba, prange": czasy_prange["Numba: prange"],
"Numba, tablica znanych wyników":
czasy_collatz["Numba: tablica znanych wyników"],
}
wykres_czasow(podsumowanie, "Kroki Collatza dla n ≤ 100 000")
The fastest is Numba with the table of known results: a better algorithm, compiled, on a single core. In pure Python, too, the better algorithm on a single core beats four processes. The order of the rungs on the ladder of laziness is no accident:
Algorithm first. The table of known results gives a several-fold speedup, on a single core and without new tools.
Then compilation. Numba speeds up loops that cannot be vectorized tens of times, but it will not replace a library such as LAPACK, and it computes only with machine numbers.
Cores last. They give a speedup of at most the number of cores, and less in practice. Threads in pure Python give nothing.
References#
S. K. Lam, A. Pitrou, S. Seibert, Numba: a LLVM-based Python JIT compiler, LLVM-HPC 2015; the Numba documentation (the chapters on
parallel=Trueandfastmath).G. M. Amdahl, Validity of the single processor approach to achieving large scale computing capabilities, AFIPS 1967.
The Python documentation: the modules
concurrent.futures,multiprocessing(process start methods),threading; PEP 703 (CPython without the GIL).M. Gorelick, I. Ozsvald, High Performance Python, 2nd ed., O’Reilly 2020, the chapters on compilation and on the
multiprocessingmodule.
Exercises#
★ Check which loops the compiler turns into a formula:
s += i,s += i * i,s += i**3,s += i % 7,s += 1 / (i + 1). Measure the time for \(n=10^3\) and \(n=10^6\) and look at the machine code (inspect_asm).★★ Compile with Numba the function
krok_zycia_petlefrom part 5, rewritten for auint8array, and compare it with the functionkrok_zyciafrom Lab 8 (np.roll) for \(200\times200\) and \(2000\times2000\) boards. Which version wins? How much does the modulo division in the innermost loop cost, and how can it be avoided?★★ Measure from which \(N\) on a new pool of four processes pays off, including its startup. Plot the time of a single process and the time of the pool as functions of \(N\).
★★ Write a version of
kroki_rownoleglethat returns only the record: the number with the largest number of steps, and that number of steps. Check in the Numba documentation which reductions can be computed in aprangeloop.★★★ Estimate the area of the lemniscate from Lecture 5 by the Monte Carlo method in Numba with a
prangeloop. Is the result the same on every run? How can you make it reproducible?