from numba import config
# Same process-wide singleton as in the intro notebook: NRT allocation
# counting has to be switched on before *any* function is compiled. It
# isn't needed until "The loop, lowered", but this is where it must live.
config.NRT_STATS = True
import contextlib
import io
import re
import tracemalloc
import numpy as np
from numba import jit
from numba.core.runtime import rtsysWhy write the loop?
The pitch for Numba is usually “add a decorator, keep your NumPy code, go faster”. That much is true, and the intro notebook measured it. But it invites an obvious follow-up: if the decorator is free, why does anybody bother writing out the loops by hand — the very thing NumPy exists to spare you?
This notebook answers that with one function, evaluated three ways: as NumPy broadcasting, as the same source handed to Numba, and as an explicit loop nest. At each step we look at what the compiler actually produced and what it cost in memory, so that the final comparison is a reading rather than a claim.
The kernel
The test function is a 2-D Ricker wavelet — the “Mexican hat”, the Laplacian of a Gaussian, a real kernel used for blob detection in images and as a source wavelet in seismics:
\[ \psi_\sigma(x, y) = (1 - r^2)\, e^{-r^2 / 2}, \qquad r^2 = \frac{x^2 + y^2}{\sigma^2} \]
It is chosen for one structural reason: \(r^2\) appears twice. That single shared subexpression is the whole story of this notebook, and it is the most ordinary thing in the world to write — you compute a quantity once and use it in two places.
The NumPy spelling evaluates it on the outer product of an \(x\)-range and a \(y\)-range, using the broadcasting rule: reshape \(x\) into a column and \(y\) into a row, and every binary operation between them spans the full \(M \times N\) grid.
The grid below is deliberately big — one array is about 127 MB, comfortably past the last-level cache of a desktop CPU (scale it up if you are on a server part with a very large L3). That is not incidental, and it is the one parameter worth keeping if you repeat this. A temporary that fits in cache is nearly free: storing it and reading it back never reaches DRAM, so removing it buys almost nothing, and what differences remain come from your C library’s page-recycling policy rather than from the code. At a cache-sized grid the ordering of the versions below is not even stable between machines. Sized as it is here, every intermediate has to make the round trip to main memory, which is the effect this notebook is about.
def f_numpy(x, y, σ):
"""Ricker wavelet on the grid spanned by 1-D `x` and `y`."""
r2 = (x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2) / (σ * σ)
return (1.0 - r2) * np.exp(-0.5 * r2)M = 3600
N = 4400
σ = 1.5
x = np.linspace(-4.0, 4.0, M)
y = np.linspace(-4.0, 4.0, N)
CELL = M * N * 8 # bytes in one (M, N) float64 array — our unit of memory
print(f"grid: {M} × {N} = {M * N:,} points, {CELL / 1e6:.2f} MB per array")grid: 3600 × 4400 = 15,840,000 points, 126.72 MB per array
t_numpy = %timeit -o f_numpy(x, y, σ)50.4 ms ± 150 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
The same source, compiled
Numba’s @jit is a decorator only by convention. It is an ordinary function that takes a function and returns a compiled dispatcher, so we can apply it to f_numpy after the fact, without editing a character of it. Nothing below is a rewrite — it is the identical code object, run through the compiler.
The string argument is the type signature: f8[::1] is a contiguous 1-D float64 array, f8 a scalar, and f8[:, ::1] the C-contiguous 2-D array coming back. Supplying it forces compilation now, at definition time, instead of on first call — and it is what lets every stage below be inspected without running anything.
SIG = "f8[:, ::1](f8[::1], f8[::1], f8)"
f_numba = jit(SIG, nopython=True, nogil=True)(f_numpy)
print("compiled from the very same function:", f_numba.py_func is f_numpy)compiled from the very same function: True
t_numba = %timeit -o f_numba(x, y, σ)43.6 ms ± 78.6 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Faster, and for free. But note how much faster — this is a fully typed, fully compiled, no-Python-objects-involved version of a function whose Python-level overhead was already amortised across sixteen million grid points. If compilation were the whole story we would expect far more than this. Almost all of the time is going somewhere @jit did not touch.
Where the time went: fusion stops where you named a value
Numba’s typed IR shows what the array-expression optimiser decided. Every fused elementwise computation becomes a single arrayexpr node — one generated loop over the grid, one array allocated to hold its result. Counting those nodes counts the passes over memory.
def typed_ir(fn):
"""`inspect_types()` prints to stdout; capture it so we can measure it."""
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
fn.inspect_types()
return buf.getvalue()
def arrayexpr_nodes(fn):
return [
line.lstrip("# ").strip()
for line in typed_ir(fn).splitlines()
if "= arrayexpr(" in line
]
OP = re.compile(r"<built-in function (\w+)>|<ufunc '(\w+)'>")
def fused_ops(node):
"""The elementwise operators this one generated loop merged together."""
return [builtin or ufunc for builtin, ufunc in OP.findall(node)]
for node in arrayexpr_nodes(f_numba):
target, ops = node.split(" = ", 1)[0], fused_ops(node)
print(f"{target:18s} ← one loop over {len(ops)} ops: {', '.join(ops)}")r2 ← one loop over 4 ops: truediv, add, pow, pow
$binop_mul210.31 ← one loop over 4 ops: mul, sub, exp, mul
Two nodes, not one. Read the first: it is r2, the whole (x² + y²)/σ² subexpression fused into one loop. The second is (1 - r2) * exp(-0.5 * r2), fused into another. Eight elementwise operators — every one of which NumPy would have evaluated on its own, allocating as it went — became two generated loops. The fuser did excellent work within each, and then stopped dead at the boundary between them.
It had no choice. The optimiser’s unit of value is an array. r2 is consumed twice, so between the two loops it has to exist somewhere addressable, and the only place an array can exist is memory: a full 127 MB round trip out to DRAM and back, for a quantity each element needs for about three floating-point operations. That is the time @jit could not recover.
Memory, measured
tracemalloc records every allocation CPython and NumPy’s data allocator make — and Numba’s runtime (NRT) allocates array data through that same NumPy allocator, so both versions are visible to the same instrument. get_traced_memory() reports the peak bytes live at once, which is exactly the footprint question: not how many temporaries were created, but how many had to coexist.
def peak_arrays(fn, *args):
"""Peak simultaneously-live memory, in units of one output array."""
fn(*args) # warm up: compile, and let NumPy's lazy machinery settle
tracemalloc.start()
tracemalloc.reset_peak()
fn(*args)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak / CELL
p_numpy = peak_arrays(f_numpy, x, y, σ)
p_numba = peak_arrays(f_numba, x, y, σ)
print(f"f_numpy peak: {p_numpy:.2f} full-size arrays")
print(f"f_numba peak: {p_numba:.2f} full-size arrays")f_numpy peak: 4.00 full-size arrays
f_numba peak: 2.00 full-size arrays
Four against two, and both land on whole arrays exactly — this is structure, not noise.
f_numba’s two are precisely the two arrayexpr nodes: r2, and the result. But four is a strange number for f_numpy. Counting the operators NumPy has to evaluate one at a time gives six full-size temporaries — x² + y², that divided by σ² (which is r2), 1 - r2, -0.5 * r2, its exp, and the final product — so why is the peak not six? And once you accept that some get freed along the way, why exactly four and not five?
Don’t reason about it; watch it. Every NumPy array runs __array_finalize__ on its way into existence and __del__ on its way out, so a subclass can log the live count as the expression evaluates.
class Traced(np.ndarray):
"""Logs the running count of live *full-size* arrays. Views are ignored."""
live = peak = created = 0
log = []
def __array_finalize__(self, obj):
if obj is not None and self.shape == (M, N):
Traced.created += 1
Traced.live += 1
Traced.peak = max(Traced.peak, Traced.live)
Traced.log.append(f"+{Traced.live}")
def __del__(self):
if self.shape == (M, N):
Traced.live -= 1
Traced.log.append(f"-{Traced.live}")
xt, yt = x.view(Traced), y.view(Traced) # cast once, before counting
f_numpy(xt, yt, σ) # warm up
Traced.live = Traced.peak = Traced.created = 0
Traced.log = []
res = f_numpy(xt, yt, σ)
del res # so the trace ends at zero
print(f"created: {Traced.created} peak: {Traced.peak}")
print("live count:", " ".join(Traced.log))created: 6 peak: 4
live count: +1 +2 -1 +2 +3 +4 -3 +4 -3 -2 -1 -0
Six created, four live at the high-water mark, and the trace says exactly where the two missing ones went. Read it left to right against the expression:
| step | event | live |
|---|---|---|
x² + y² |
allocated | +1 |
… / σ² → r2 |
allocated | +2 |
x² + y² freed — nothing refers to it now |
-1 |
|
1 - r2 |
allocated | +2 |
-0.5 * r2 |
allocated | +3 |
exp(…) |
allocated | +4 ← peak |
-0.5 * r2 freed — exp consumed it |
-3 |
|
(1 - r2) * exp(…) |
allocated | +4 ← peak again |
1 - r2 and exp(…) freed |
-3 -2 |
|
r2 freed at function exit, result at del |
-1 -0 |
That is the answer to “why four and not five”: the two -1 and -3 steps. CPython frees a temporary the instant the last operator consuming it returns — not at some later garbage collection — so x² + y² is gone before 1 - r2 is born, and -0.5 * r2 is gone before the final product is born. Five never happens, because the count comes back down between each pair of allocations. Eager evaluation is not as wasteful as the naive count of six suggests; it is just twice as wasteful as it needs to be.
The fusion we read out of the typed IR and this halved footprint are the same fact, arrived at by two instruments that share no code.
Rewriting for the fuser
If naming r2 is what blocked the fusion, then not naming it should unblock it. Write the subexpression out twice and the two arrayexpr nodes should become one.
def f_numpy_inlined(x, y, σ):
X2 = x.reshape(-1, 1) ** 2
Y2 = y.reshape(1, -1) ** 2
return (1.0 - (X2 + Y2) / (σ * σ)) * np.exp(-0.5 * (X2 + Y2) / (σ * σ))
f_numba_inlined = jit(SIG, nopython=True, nogil=True)(f_numpy_inlined)
nodes = arrayexpr_nodes(f_numba_inlined)
print("arrayexpr nodes:", [n.split(" = ", 1)[0] for n in nodes])
print(f"peak: {peak_arrays(f_numba_inlined, x, y, σ):.2f} full-size arrays")arrayexpr nodes: ['X2', 'Y2', '$binop_mul250.38']
peak: 1.00 full-size arrays
t_inlined = %timeit -o f_numba_inlined(x, y, σ)46.7 ms ± 34.3 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Three nodes, not one — and the names say why. X2 and Y2 are real arrays, really allocated: naming them in their own statements kept them out of the fused expression, so they get materialised exactly as r2 did. So this version allocates three arrays where f_numba allocated two — one more, not one fewer, as the scoreboard’s allocs column will confirm.
What changed is not how many but how big. The array that stopped being allocated was the 127 MB r2; the two that replaced it are \((M, 1)\) and \((1, N)\), about 64 kB the pair. That is why the peak still reads 1.00: peak_arrays measures in units of a full-size array, and 64 kB rounds away to nothing. Everything spanning the grid went into the third node — one fused loop, one big array, and faster.
It is worth being precise about why it is faster, because the obvious reading is backwards. f_numpy_inlined computes \(r^2\) twice per grid point to avoid storing it once, and it wins anyway. Those three extra floating-point operations cost a couple of cycles each; the store and reload they replaced cost a 127 MB round trip to DRAM, at a couple of hundred cycles per miss. Recomputation is nearly free and memory is not, which is the exchange rate this whole notebook turns on.
And that is also the problem. Nothing about f_numpy_inlined is clearer than f_numpy — it is strictly worse to read and it repeats itself. We made the right trade by editing source text until an optimiser we cannot see changed its mind.
That is the ceiling of the array-expression style. You are not describing a computation; you are steering a pass. And you can only ever reach the fusions the pass already knows how to perform — there is no vocabulary in x * y + z for “keep this in a register”, because broadcasting has no notion of a register. Everything it can name is an array.
Saying it in loops
The loop nest has that vocabulary. Written elementwise, r2 is a local scalar: it lives in a register for the two instructions that need it and then it is gone. It never has an address, never touches DRAM, and never gets counted — not because an optimiser decided so, but because that is what the code says.
While we are down here we can also hoist x[i]² / σ². To hoist a computation is to move it out of a loop to a point where it runs less often: x[i] * x[i] * inv depends only on i, so evaluating it once per row rather than once per grid point turns \(M \times N\) evaluations into \(M\) — 15.8 million down to 3600. The inner loop then adds one pre-computed number instead of squaring and scaling from scratch.
That rearrangement has no expression in broadcasting notation at all. There is no “per row” in x.reshape(-1, 1) ** 2; it is a whole array before it is anything else, and the loop over rows that would give you somewhere to hoist to is generated out of sight.
@jit(SIG, nopython=True, nogil=True)
def f_numba_loops(x, y, σ):
M = x.shape[0]
N = y.shape[0]
res = np.empty((M, N))
inv = 1.0 / (σ * σ)
for i in range(M):
xi = x[i] * x[i] * inv # invariant in j — hoisted out of it
for j in range(N):
r2 = xi + y[j] * y[j] * inv # a scalar, in a register
res[i, j] = (1.0 - r2) * np.exp(-0.5 * r2)
return res
ref = f_numpy(x, y, σ)
print("matches f_numpy:", np.allclose(f_numba_loops(x, y, σ), ref))
print(f"arrayexpr nodes: {len(arrayexpr_nodes(f_numba_loops))}")
print(f"peak: {peak_arrays(f_numba_loops, x, y, σ):.2f} full-size arrays")matches f_numpy: True
arrayexpr nodes: 0
peak: 1.00 full-size arrays
t_loops = %timeit -o f_numba_loops(x, y, σ)39.7 ms ± 30.8 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Zero arrayexpr nodes — there is no array expression left to optimise, only scalar arithmetic and stores — and a peak of exactly one array: the output. That is the floor. You cannot compute an \(M \times N\) result in less than \(M \times N\) words, and this version uses no word more.
Numba’s own runtime agrees, and counts rather than weighs — so unlike the peak in units of full-size arrays, it will not let a small allocation round away. NRT counts every allocation the compiled function makes, including the reference-counted handle it wraps around each array argument. Measure that overhead rather than assume it, with a function that allocates nothing:
@jit("f8[::1](f8[::1], f8[::1], f8)", nopython=True, nogil=True)
def wrappers_only(x, y, σ):
return x # hand back an input unchanged — nothing new can be allocated
def nrt_allocs(fn, *args):
"""NRT allocations for one call, once the function is compiled."""
fn(*args)
before = rtsys.get_allocation_stats()
fn(*args)
after = rtsys.get_allocation_stats()
return after.alloc - before.alloc
BASELINE = nrt_allocs(wrappers_only, x, y, σ)
total = nrt_allocs(f_numba_loops, x, y, σ)
print(f"wrapping 2 array arguments, computing nothing: {BASELINE} allocations")
print(f"f_numba_loops: {total} allocations")
print(f" difference: {total - BASELINE}")wrapping 2 array arguments, computing nothing: 2 allocations
f_numba_loops: 3 allocations
difference: 1
Two allocations are pure argument-wrapping overhead, and the difference is one: res. No temporary exists to be counted, at any size. This is the instrument the scoreboard will use to put every version on the same footing — the peak tells you what it cost, this tells you what was created.
Was it the hoist?
Two things changed at once, so separate them. Here is the same loop with the invariant left inside, transcribed straight from the formula:
@jit(SIG, nopython=True, nogil=True)
def f_numba_loops_naive(x, y, σ):
M = x.shape[0]
N = y.shape[0]
res = np.empty((M, N))
for i in range(M):
for j in range(N):
r2 = (x[i] * x[i] + y[j] * y[j]) / (σ * σ)
res[i, j] = (1.0 - r2) * np.exp(-0.5 * r2)
return rest_naive = %timeit -o f_numba_loops_naive(x, y, σ)42.1 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Under ten percent behind the hoisted version — against the 1.8× that merely writing the loop bought in the first place. LLVM’s loop-invariant code motion had already found most of that rearrangement on its own: it is a textbook pass, and x[i] provably does not change across the inner loop.
So the hoist was not the win. The win was the scalar, and the naive loop gets it too: a direct transcription of the maths, with no optimisation thought applied at all, already beats the version we contorted for the fuser. That is the actual claim of this notebook — not that hand-tuned loops beat NumPy, but that saying plainly what you mean, one element at a time, gives the compiler more to work with than the array notation can express.
The loop, lowered
One look at what the loop became, because the intuition here runs backwards: writing out a scalar loop feels like giving up vectorisation. The LLVM IR says otherwise.
def llvm_ir(fn):
return list(fn.inspect_llvm().values())[0]
ARITH = ("fmul", "fadd", "fsub", "exp")
for line in llvm_ir(f_numba_loops).splitlines():
if "x double>" in line and any(op in line for op in ARITH):
if not line.startswith("declare"):
print(line.strip())%10 = fmul <8 x double> %wide.load, %wide.load
%11 = fmul <8 x double> %broadcast.splat17, %10
%12 = fadd <8 x double> %broadcast.splat, %11
%13 = fsub <8 x double> splat (double 1.000000e+00), %12
%14 = fmul <8 x double> %12, splat (double -5.000000e-01)
%15 = tail call <8 x double> @llvm.exp.v8f64(<8 x double> %14)
%16 = fmul <8 x double> %13, %15
<8 x double> — LLVM rewrote the scalar loop we wrote into SIMD, eight grid points per instruction, exp included. Line for line this is the Ricker wavelet: square, scale by \(1/\sigma^2\), add the hoisted row term, \(1 - r^2\), \(-r^2/2\), exponentiate, multiply. Seven vector instructions per eight grid points, and nothing between them goes to memory.
Writing the loop out did not cost us vectorisation — that is the intuition worth correcting. It is also not what separates the three versions: all of them vectorise, and all of them get the vector exp. What separates them is how much scaffolding had to be built around the arithmetic.
for name, fn in [
("f_numba", f_numba),
("f_numba_inlined", f_numba_inlined),
("f_numba_loops", f_numba_loops),
]:
print(f"{name:20s}{len(llvm_ir(fn).splitlines()):6d} lines of LLVM IR")f_numba 5209 lines of LLVM IR
f_numba_inlined 4679 lines of LLVM IR
f_numba_loops 756 lines of LLVM IR
The array-expression versions generate roughly seven times the IR, and it is not arithmetic. arrayexpr has to emit a loop that works for any pair of broadcast-compatible shapes and strides: shape checks, stride-0 dispatch, several specialised versions of the loop body to pick between at runtime. The hand-written loop needs none of it, because the shapes are the two range() bounds and the access pattern is written down.
That is the last piece of the timing: f_numba_inlined and f_numba_loops peak at the same memory — one full-size array’s worth each — yet the loop is still faster. The gap is not bandwidth and it is not FLOPs. It is the per-element index arithmetic that broadcasting has to keep around because it does not know, and cannot know from the notation, that you meant one contiguous sweep.
The scoreboard
The times are the %timeit results from above, carried down by -o rather than retyped, so the table cannot drift out of step with the cells that produced it. The memory columns are measured here, on the spot, by the two instruments the notebook already built.
rows = [
("f_numpy", "broadcasting, interp.", f_numpy, t_numpy),
("f_numba", "same source, compiled", f_numba, t_numba),
("f_numba_inlined", "rewritten for fuser", f_numba_inlined, t_inlined),
("f_numba_loops_naive", "loops, as written", f_numba_loops_naive, t_naive),
("f_numba_loops", "loops, hoisted", f_numba_loops, t_loops),
]
print(f"{'':20s}{'':23s}{'ms':>7s}{'vs np':>7s}{'peak':>6s}{'allocs':>7s}")
for name, note, fn, t in rows:
peak = peak_arrays(fn, x, y, σ)
n = "—" if fn is f_numpy else f"{nrt_allocs(fn, x, y, σ) - BASELINE:d}"
print(
f"{name:20s}{note:23s}{t.best * 1e3:7.2f}"
f"{t_numpy.best / t.best:6.2f}×{peak:6.1f}{n:>7s}"
)
print("\npeak = tracemalloc: live memory high-water mark ÷ one output")
print(" array")
print("allocs = NRT: arrays created, any size, less the argument-wrapping")
print(" baseline (NRT is Numba's; it says nothing about f_numpy)") ms vs np peak allocs
f_numpy broadcasting, interp. 50.26 1.00× 4.0 —
f_numba same source, compiled 43.51 1.16× 2.0 2
f_numba_inlined rewritten for fuser 46.67 1.08× 1.0 3
f_numba_loops_naive loops, as written 40.71 1.23× 1.0 1
f_numba_loops loops, hoisted 39.67 1.27× 1.0 1
peak = tracemalloc: live memory high-water mark ÷ one output
array
allocs = NRT: arrays created, any size, less the argument-wrapping
baseline (NRT is Numba's; it says nothing about f_numpy)
Read down the columns: peak footprint \(4 \to 2 \to 1\), and time falling with it. Every row does the same sixteen million evaluations of the same wavelet; all that changed is where the intermediates were allowed to live.
This is where the grid size from the very beginning earns its keep. There is a second cost to allocating a fresh array that has nothing to do with bandwidth: the memory is not memory the process already has, so the kernel hands over its pages one at a time, on demand, trapping on each one the first time it is written. Whether a page is genuinely fresh or recycled from something the allocator is already holding depends on your C library’s policy and on what the process happened to allocate earlier — which is to say, on nothing in this notebook. At a cache-sized grid that effect is the dominant term, and these timings would say more about glibc than about fusion; the rows would reorder between one machine and the next. At 127 MB an array it is a few percent, and what is left is the memory traffic itself.
The two memory columns disagree in one place, and the disagreement is the point. f_numba_inlined allocates more arrays than f_numba — three against two — while peaking at half the memory, because the two extra ones are the kilobyte-sized X2 and Y2 and the one it stopped allocating was the 127 MB r2. Counting allocations and weighing them answer different questions, and a version can win on one while losing on the other. Only f_numba_loops wins on both: one array allocated, one array’s worth of memory, nothing else created at any size.
The ordering that surprises people is the one in the middle: f_numba_inlined beats f_numba — the version computing \(r^2\) twice beats the version computing it once and keeping it. That is not measurement noise; those two rows are stable to a few percent across every protocol tried, and they sit two milliseconds apart. Arithmetic is not the scarce resource here, and no row in this table was made faster by doing less of it.
What you traded
Going down a level of abstraction is not free, and it is worth being precise about the bill.
You gave up notation. f_numpy is four lines that look like the formula and work for any broadcastable shapes; f_numba_loops is nine lines that hard-code a rank-2 loop nest, and the next kernel needs a new one. You gave up NumPy’s whole library — no @, no np.fft, no scipy — inside the compiled region, and you took on responsibility for index bounds that broadcasting was checking for you.
What you bought is the register. Array notation can only name arrays, so every intermediate it names must be materialised, and its optimiser can only fuse away the ones it recognises. The loop can name a scalar, which is to say it can talk about the top of the memory hierarchy — and on modern hardware, where a DRAM round trip costs a couple of hundred cycles and a multiply costs about four, that is usually where the performance lives.
The same trade, at a much larger scale, is what XLA and torch.compile are for: they take the array notation back and fuse it properly, so that you can write f_numpy and get f_numba_loops. That is later in this talk. The point of this notebook is what those systems are working to recover — and that Numba lets you simply go and take it, in Python, in nine lines, today.