You need: how C++ is compiled and linked, and what undefined behaviour means (C++: the essentials); new, RAII and moves (C++: ownership, moves and object lifetimes). Python habits are enough for the rest: each section says where NumPy or CPython meets the same machine.
Time for one operation, log scale, all on this M1 Pro. A load from L1 (about 1 ns) is as cheap as one fused multiply-add; a load whose address the hardware cannot predict, from a 512 MB buffer, takes about 133 ns; in that time one core running at its measured peak of 97.5 GFLOP/s could have done 97.5 x 133 = about 13,000 FLOPs derived. The same 512 MB read in address order costs about 11 ns per load, because the prefetcher fetches ahead. The rest of the page is how to stay on the left of this picture.
Each row: one idea, the number that shows it on this M1 Pro, and what it changes in the code you write.
| Idea | Measured on this M1 Pro | What to do |
|---|---|---|
| Memory is a ladder of caches | A load takes ns from L1 and about ns from DRAM when the address is unpredictable | Keep the working set small; reuse data while it is hot |
| Memory moves in 128-byte lines | Summing a matrix by columns is x slower than by rows | Walk memory in the order it is laid out |
| Layout decides what you read | Struct of arrays is x faster than array of structs for one field of eight | Group the fields that are used together; values, not pointers |
| Memory comes in 16 KB pages, lazily | A first touch costs about microseconds per page | mmap big read-only files |
| The compiler rewrites your code | At -O2 a loop of n calls became a formula with no loop | Read the assembly before guessing |
| SIMD: one instruction, four floats | Dot product: x faster with NEON and independent accumulators | Break dependency chains; let the compiler vectorise |
| The processor guesses branches | Unpredictable branch: x slower than the same loop on sorted data | Make branches predictable or remove them |
| Cores see memory in different orders | Relaxed atomics: reordered messages in 52 million; false sharing: x slower | Release/acquire to publish data; one 128-byte line per hot counter |
| Most code is memory-bound | Matrix-vector product: GFLOP/s of a GFLOP/s core | Count bytes, not FLOPs, for LLM decode |
| Measure, with counters | Column walk: instructions per cycle against | Profile first; microbenchmarks mislead |
| The ABI is a binary contract | dot(const float*, ...) is the symbol __ZN9ggml_like3dotEPKfS1_i | extern "C" at language boundaries |
Apple M1 Pro (8 performance and 2 efficiency cores, 16 GB, macOS 27), Apple clang 17 (LLVM clang 23 for ThreadSanitizer), recorded 2026-10-05. Timings are the first of three runs with the spread of all three beside them; the laptop was in normal use (load average about 5 to 12 on 10 cores), so treat the second digit of any timing as noise. Programs, outputs and the script that reproduces them: src/cb/.
total += x costs tens of nanoseconds whatever the data looks like, because the interpreter's own work dwarfs the memory access (Python: CPython internals and performance). Once a loop compiles to a few machine instructions, as in C++, Rust or inside NumPy, the memory system is what is left. That is why numpy.sum on a contiguous array is fast and on a strided view can be much slower.An addition takes a fraction of a nanosecond; fetching a number from DRAM takes about a hundred. To hide the gap the chip keeps copies of recently used memory in caches, each level bigger and slower than the one before: on this M1 Pro, 128 KB of L1 per performance core, 12 MB of L2 shared by the 8 performance cores, a system level cache shared with the GPU (size unpublished), then 16 GB of DRAM, "up to 200GB/s" for the chip (Apple).
Plate widths are log-scaled sizes and the latencies are this machine's measured pointer-chase times (next figure); the system level cache's size is unpublished, so its plate has no number.
Measured: ladder.cpp, one node per 128-byte line, best of 3 timings inside each run; three runs in random order, two in address order (load average per run: ). The linear scale shows how far DRAM is.
Grow the pointer chase's buffer from 4 KB to 1 GB and each level overflows in turn. The chart climbs the 37 sizes in five stretches, then adds the address-order runs:
A hash-table lookup or linked-structure walk over a big table pays the right-hand end of this chart per hop; a scan over a contiguous array pays the bottom curve or less. Shrinking the working set by one level (from DRAM-sized to L2-sized) is often worth more than any change to the arithmetic.
Registers sit inside the core: 31 general of 64 bits and 32 SIMD of 128 bits, read in the same cycle. The efficiency cores have 64 KB of L1 and share 4 MB of L2. Sizes from sysctl on this machine:
Random order, run 1, with the range of the three runs (the system level cache sits between L2 and DRAM and shows only as a softer ramp):
illustrative Each row of the grid is one 128-byte line of 32 integers; a line turns solid when fetched, a slot is outlined when used, the red frame is the element being added. The matrix is shrunk to 16 rows of 32 integers and the cache to 8 lines (least recently used evicted) so that rows overflow it as a 4096 x 4096 matrix overflows L1 and L2 (the real L1 holds 1,024 lines). No prefetching is modelled; the measured ratio appears at the last step.
Caches hold cache lines, aligned blocks of 128 bytes on this M1 Pro (hw.cachelinesize; 64 on most Intel and AMD processors). Reading one byte brings its whole line into L1. Two habits follow. Spatial locality: use the neighbours of what you just read, since they arrived with it (a line holds 32 floats, so reading them in order costs one trip to memory per 32 numbers). Temporal locality: reuse data soon, before other data evicts it; blocked ("tiled") matrix multiplication is this idea.
The test: a 4096 x 4096 matrix of 32-bit integers (64 MB) stored row after row, as C++ and NumPy lay it out by default, summed row by row and then column by column. Same additions, same answer.
Three runs: x. Down a column, consecutive elements are 4096 x 4 = 16 KB apart, so every addition needs a new line and uses 4 of its 128 bytes; by the time the loop returns for the next column the line has been evicted. Row order uses every byte of every line, the prefetcher sees a simple stream, and the compiler can add 4 integers per instruction (section 6): cache lines and SIMD multiply.
rowcol.cpp) and its recorded outputa.sum(axis=0) and a.sum(axis=1) face this choice; NumPy's reductions walk memory well either way, but your own loops over a[:, j], or a Fortran-ordered array handed to code expecting C order, do not. PyTorch's .contiguous() exists for this reason.A C++ struct is laid out exactly as declared, fields in order, under two rules. Alignment: each type must start at an address divisible by its alignof (4 for int32_t, 8 for double or a pointer), so it loads in one go. Padding: the compiler inserts unused bytes to satisfy alignment, between fields and at the end (so the next array element is aligned too); sizeof includes them.
Predict. Bad holds 1 + 8 + 4 = 13 bytes of data. What does sizeof(Bad) print? And Good, the same fields largest first?
24 and 16 bytes: 11 of Bad's 24 bytes are padding (7 after flag so that score starts at 8, and 4 at the end so that the size is a multiple of its alignment, 8). Ordering fields from largest to smallest alignment removes most of it: a third fewer cache lines for an array of them. Clang's -Wpadded lists every hole. The last line returns in section 8.
An array of structs (AoS, std::vector<Token>) stores records one after another; a struct of arrays (SoA) stores one array per field. AoS is what object-oriented code produces; SoA is what columnar formats (Arrow, Parquet), dataframes and tensors use. The test: 20 million token records of 8 four-byte fields (32 bytes each), summing one field, then all eight.
Token is 8 fields of 4 bytes: id, logprob, user, pos, temp, top_p, seq, flags. Stored as AoS, four records fill one 128-byte line; the grid is 32 records, 8 lines.user touches every line: 8 lines fetched, 1,024 bytes moved to use 128, 4 of every 32 bytes (12.5%).user fetches 1 line and uses all 128 bytes; the other 7 arrays are never touched.Record and line sizes are the program's (sizeof(Token) = 32, 128-byte lines); 32 records stand in for the 20 million measured.
The three runs, field by field:
s += x on floats happen in order (float addition is not associative), and each add waits about 3 cycles for the previous one. With -ffast-math the 8x appears: AoS ns, SoA ns. Section 6 explains why.aos_soa.cpp) and its recorded outputA tensor is SoA taken to the limit: one contiguous buffer per quantity. llama.cpp's quantised weights are a deliberate AoS: each block_q4_0 packs one 2-byte scale with the 32 four-bit weights it scales (18 bytes), because the dot product needs both together (C++: reading llama.cpp reads its kernels).
Values, not pointers. A container of pointers is a pointer chase too: every make_unique calls the allocator and puts the object somewhere else on the heap. Ten million separate heap objects cost about x as much as one reserved vector of values. How malloc finds space is Memory allocators' subject.
Three runs: ms for the heap objects against ms reserved. A growing std::vector reallocates when full, moving every element into a buffer about twice as big; growth without reserve moved the buffer 25 times but cost little, because doubling makes the total copying about twice the final size. The last lines show the small-string optimisation: a std::string object here is 24 bytes, and strings of up to 22 characters live inside it with no heap allocation. Rules: reserve when you know the size, store values rather than pointers, reuse buffers across iterations, and make large objects movable so containers move rather than copy them (the ownership page covers moves).
Addresses are virtual, mapped one page at a time; on Apple silicon a page is 16 KB (hw.pagesize printed 16384; 4 KB on most Linux machines). The mechanism (page tables, the TLB, page faults, the page cache) belongs to Virtual memory. Two consequences for C++ code, measured here: new of a big block only reserves addresses, and the first touch of each page is a page fault costing about microseconds (three runs: ); and mmap of a 512 MB file took ms whatever its size, with pages read only when touched. That is why llama.cpp maps model files: loading is nearly instant, processes running the same model share the physical pages, and a restart finds the weights still cached (Local and on-device inference measures it for safetensors and GGUF).
Filling fresh memory took ms the first time and ms the second; the difference over 16,384 page faults gives the per-fault cost. Reading 8 bytes spread through the mapped file cost just 8 page faults; reading the whole file with read() took ms before the first byte was usable and doubled the memory in use. Touching every page is fast only when the file is in the page cache (minor faults, about 25 ms here); in run 1 other programs had pushed it out of RAM, so the touch took about 0.9 s of major faults, and its read() afterwards was fast because the mapping had just brought the file back.
The pinned llama.cpp (commit 8e16421) maps the model with hints to the kernel about the access pattern:
src/llama-mmap.cpp lines 482 to 498. The operating system can also drop clean mapped pages under memory pressure and re-read them later instead of swapping. From Python, numpy.memmap, safetensors' lazy loading and torch.load(..., mmap=True) are the same system call: "the model loaded instantly but the first token was slow" is page faults paid on first use.
Clang (via LLVM) translates C++ into machine code; assembly is its readable text. Reading a little of it is the only reliable way to know what your C++ became: clang++ -O2 -S file.cpp -o -, or Compiler Explorer (godbolt.org), which colours each source line and its instructions alike.
Predict. At -O2, how many times does sum_squares(1000) call square? How many times does its loop run?
Three transformations decide whether an abstraction is free:
-flto).virtual call loads the object's vtable pointer, loads the function's address from it and jumps there, which also blocks inlining. When the compiler can prove the exact type (here the class is final), it calls or inlines directly. (C++: classes, templates and the standard library measures what dispatch costs.)-Rpass=loop-vectorize (done), -Rpass-missed=loop-vectorize (refused) and -Rpass-analysis=loop-vectorize (why) (LLVM vectoriser docs).final classarea_of(const Shape&): virtual call
Load the vtable pointer from the object ([x0]), load the function pointer at offset 16 of the vtable, jump (br x1).
area_of_square(const Square&): devirtualised and inlined
Load side (offset 8, after the vtable pointer), multiply, return.
The vectoriser's report for the dot products of the next section:
dot_auto (line 16) was "vectorized (vectorization width: 4, interleaved count: 4)". The assembly in the next section shows that only the multiplications were; the additions still run one at a time, in source order, because float addition may not be reordered. Always confirm in the assembly.This laptop runs ARM64 (AArch64). Each line is one instruction, written operation destination, source, source:
| You see | It means |
|---|---|
x0 .. x30, w0 .. w30 | The 64-bit general registers; w is the low 32 bits of the same register. sp is the stack pointer. |
s0, d0, q0, v0.4s | The SIMD and float registers: one 32-bit float, one 64-bit double, the whole 128 bits, or the 128 bits seen as 4 floats ("4s" means 4 single-precision lanes; Apple's assembler prints fmla.4s). |
| arguments and result | By the calling convention (AAPCS64), the first 8 integer or pointer arguments arrive in x0..x7, float ones in v0..v7, and the result goes back in x0 or s0/d0. |
ldr, str, ldp | Load a register from memory, store it, load a pair. [x0, #8] is "the address in x0 plus 8"; [x0], #4 loads then adds 4 to x0. |
add, mul, madd, fadd, fmadd, fmla | Integer and float arithmetic; fmadd/fmla are fused multiply-add (a + b x c in one instruction, one rounding). |
cmp, subs, b.ne, b.lt, cbz, tbz | Compare (set flags), then branch if not equal, less than, if zero, if a bit is zero. A loop ends with one of these jumping back to its label. |
bl, br, ret | Call a function, jump to an address held in a register, return. |
SIMD (single instruction, multiple data) applies one operation to a short vector held in one wide register. On ARM it is NEON: 32 registers of 128 bits, each 4 floats, 8 16-bit values or 16 bytes; fmla v0.4s, v1.4s, v2.4s does four multiply-adds at once. On x86 the same ideas are SSE (128 bits), AVX2 (256 bits: 8 floats) and AVX-512 (16 floats), with intrinsics such as _mm256_fmadd_ps (Intel intrinsics guide). This M1 Pro also reports the 8-bit dot-product extension (FEAT_DotProd: 1) but not BF16, I8MM or SME (all 0 in sysctl); llama.cpp's quantised kernels check for exactly these features.
Three ways to get SIMD code: let the compiler vectorise a plain loop, write intrinsics (C functions that map one to one onto SIMD instructions, from <arm_neon.h>; Arm intrinsics reference), or call a library that did (BLAS, Accelerate, ggml). A dot product, the core of every matrix product, written three ways and compiled a fourth:
Timed on two vectors of 4096 floats (32 KB, inside L1) and on vectors far bigger than the caches:
The plain loop at -O2 is barely faster than scalar; with -ffast-math it matches hand-written intrinsics, about x faster than scalar in L1. From DRAM every fast version hits the same wall, about 56 GB/s for one core (section 9).
Each box is one instruction, as wide as the lanes it works on and as tall as the cycles it takes, on one scale for all three; the dashed line is the dependency carried in s0.
Same 16 products, same answer: one chain takes 64 cycles, four independent vector chains take 4 per block. In the figure each box is one instruction, as wide as the lanes it works on and as tall as the cycles it takes; time runs down.
a[i] = (i % 17) / 4, b[i] = (i % 13) / 2), each bar one product. The clock counts cycles on the critical path with published latencies (4 cycles for fmadd, fmul and fmla, 3 for fadd and faddp: Dougall Johnson's Firestorm tables).fmadd. Each one adds into s0, so it waits 4 cycles for the previous one: 64 cycles for the block, 4 per element.-O2: vector multiply, serial add. Four fmul.4s multiply all 16 pairs at once, 4 cycles; then the 16 products are added into s0 one by one, in source order, 3 cycles each: 52 cycles, 3 per element once the loop runs.fmla.4s, one per register v0..v3, each doing 4 multiply-adds: all 16 in 4 cycles, 0.25 cycles per element.v0 += v1 and v2 += v3 together, then v0 += v2, then two pairwise adds (faddp): 12 more cycles, 16 for this lone block. The result, 86.75, is the scalar loop's (these small numbers add exactly). In a long loop the reduction happens once, so the steady cost is the chain's step.The time is set by the longest chain of instructions that wait for each other, not by how many instructions there are. Independent accumulators break the chain; SIMD lanes multiply the work per instruction. A small model predicts the measured times from those two latencies and a 3.2 GHz clock (inferred: the add chain's measured ns per element divided into 3 cycles gives GHz):
On 67-million-element vectors the serial loops printed and the 16-accumulator loops ; the exact sum (exact arithmetic in Python on the same inputs) is . The serial float sum is 23% low: once the running total is large, adding a small product rounds most of it away, while sixteen smaller partial sums lose less. Reordering is not "less accurate" in general; it is different, here better (Numerical computing owns summation error). -ffast-math also assumes there are no NaNs or infinities, which can silently break code that checks for them. Prefer intrinsics, a local permission such as clang's #pragma clang fp reassociate(on) at the top of one function (checked here: the plain loop then compiles to fmla.4s accumulators, src/cb/code/reassoc.cpp), or a library.
np.dot on float32 calls a BLAS library that does all of this (on macOS, Accelerate may use Apple's matrix hardware). Python's sum() over floats is the serial chain plus the interpreter; math.fsum trades speed for an exactly rounded result.The inner loop is the block that ends with b.ne back to its label:
ggml's float dot product is this exact design: on NEON, GGML_F32_STEP 16 floats per iteration as 4 registers of GGML_F32_EPR 4 lanes, each with its own accumulator.
A core works on hundreds of instructions at once in a pipeline. At an if it cannot wait to learn which way to go, so a branch predictor guesses from the branch's history and the core runs ahead on the guess. A right guess is free; a misprediction throws away the work on the wrong path. The test counts and sums the bytes that are at least 128 in 32 million random bytes, then the same bytes sorted:
branch.cpp)Predict. Compiled normally at -O2: how much faster is the sorted run?
-O2
No difference, and both fast: the compiler removed the branch, turning if (v[i] >= 128) s += v[i] into SIMD code that compares 16 bytes at once and adds through a mask, so there is nothing to predict. The famous result (a Stack Overflow question with tens of thousands of votes) appears only when the branch stays. Built with -DKEEP_BRANCH, an empty asm volatile("") inside the if forces a real branch (tbz, "test bit and branch if zero", on the byte's top bit):
-O2, branch kept
Unsorted, the predictor is wrong about half the time; sorted, almost never. One misprediction, derived: ( - ) ns / 0.5 mispredictions per element = ns, about cycles at 3.2 GHz (an upper estimate: it includes other work the wrong path delayed). Three runs: x.
In hot loops over data you cannot sort, prefer branch-free forms (a conditional select, s += v[i] >= 128 ? v[i] : 0, which compiles to csel or a SIMD mask) and check in the assembly that the compiler did it. [[likely]] and [[unlikely]] change code layout, not the predictor's hit rate. NumPy's a[a >= 128].sum() and np.where are branch-free by construction: a mask over the whole array, the style the compiler found here.
A data race (two threads touching the same memory, at least one writing, nothing ordering them) is undefined behaviour in C++; threads, locks and atomics as operating-system mechanisms belong to Concurrency. What the hardware adds: cores do not see each other's writes in the order they were made. Each core writes into a private store buffer before the shared caches and runs loads early, out of order. x86 keeps stores in order (a strong model); ARM, including this chip, does not (a weak model); the compiler may reorder too. So C++ defines a memory model, and each atomic operation (a std::atomic<T> read or write that can never be torn) states the order it needs (cppreference):
| Order | In plain words | ARM64 code (real) |
|---|---|---|
relaxed | This operation is atomic; no promise about the order of other memory operations around it. Right for counters and statistics. | plain ldr / str |
release (on a store) | Every write I made before this store is visible to whoever sees this store. "Publish." | stlr (store-release) |
acquire (on a load) | If I see a released value, I also see everything written before it. "Subscribe." | ldapr (load-acquire) |
seq_cst (the default) | Acquire and release, plus one single order of all such operations that every thread agrees on. Easiest to reason about, slightly dearer. | stlr / ldar |
The standard test is message passing: thread A writes data = 1, then flag = 1; thread B reads flag, then data. The program runs it on a million independent slots, fifty times, 52,428,800 trials per memory order.
data = 1 then flag = 1; thread B, on another, loads flag then data. Both start at 0 in the shared caches.str instructions promise nothing about which store becomes visible first: here flag = 1 reaches the shared cache while data = 1 still waits.flag (1), then data (0): the message arrived without its contents. Measured with relaxed atomics: of trials. A core that runs B's load of data early, before its load of flag, produces the same outcome.stlr keeps earlier writes first. With release on the flag's store, every write A made before it becomes visible before the flag does: data = 1 lands, then flag = 1.ldapr keeps later reads after. With acquire on B's load of the flag, B's load of data cannot run before it; seeing flag = 1, B sees data = 1. Measured: trials in all three runs.illustrative The store buffer drawn here is the textbook model of what ARM's memory model allows, not a documented picture of Apple's cores; the instructions are this program's compiled code and the counts are measured.
Three runs: reordered trials with relaxed, 0 every time with release/acquire. Rare and real: a reader on this processor can see the flag before the data, so code that "works in testing" with relaxed atomics or plain variables can fail once in millions of messages in production. Release on the flag's store and acquire on its load forbid the outcome, and the instructions in the table enforce it.
litmus.cpp) and its recorded outputPlain variables are worse: the compiler deletes the wait. The same pattern with an ordinary bool ready, run 300 times, sometimes prints 0 at -O2 and never at -O0. Thread B's assembly at -O2 has no loop at all: a data race is undefined behaviour, so the compiler may assume ready cannot change while while (!ready) {} spins; a side-effect-free loop that never ends is also undefined behaviour ([intro.progress]), so it assumes the loop ends and deletes it. ThreadSanitizer (-fsanitize=thread) finds the race on any run, even one that printed 42.
From orders_asm.cpp: data.store(1, relaxed); flag.store(1, order) and flag.load(order) then data.load(relaxed).
-O0, 300 runs
-O2, 300 runs
Thread B's -O2 assembly is in src/cb/out/race_O2.s. ThreadSanitizer ran with LLVM clang 23, since Apple's sanitizer runtime does not start on macOS 27 (more undefined behaviour with sanitizers on C++: the essentials):
Coherence works per cache line: before a core writes to a line, every other core's copy is invalidated. Two threads writing different variables that share a line fight over it as if they shared data: false sharing. Four threads, each incrementing its own counter 100 million times:
Three runs: 8 bytes apart took ms against ms one line apart. 64 bytes apart is still about twice as slow ( ms), because two counters 64 bytes apart still share a 128-byte line. A trap: std::hardware_destructive_interference_size, the standard's "minimum offset to avoid false sharing" (cppreference), is 64 in this standard library (the layout output in section 3), and llama.cpp's own CACHE_LINE_SIZE is 64 on ARM as well:
false_sharing.cpp) and its recorded outputOn Apple silicon, pad hot per-thread data to 128 bytes: struct alignas(128) Padded { ... }. In Python, the GIL hides all of this in default CPython; free-threaded 3.14t brings it back (Python: concurrency, asyncio and the GIL), and NumPy and PyTorch release the GIL inside their kernels, so their worker threads run this machine-level code for you.
A kernel is limited either by arithmetic or by bytes from memory; the roofline (attainable FLOP/s = min(peak, arithmetic intensity x bandwidth)) says which. The concept, the ridge point and decode and prefill bounds belong to Performance math; the hardware root's Roofline lab plots these CPU roofs beside the M1 GPU and datacenter chips. Here is the C++ that measured the CPU side (roof.cpp, -O3 -ffast-math, three runs each):
The matrix-vector product is LLM decoding. One token multiplies every weight matrix by one vector: each weight is read once for one multiply-add, 2 FLOPs per 4 bytes in fp32 (intensity 0.5), far left of the ridge. The measured matvec sits right on the memory roof, 0.5 x bandwidth, so decode speed is set by bytes: tokens per second are at most bandwidth over bytes of weights. That is why quantisation and batching speed up serving (Topic: inference-and-serving).
The peak loop runs 24 independent fmla.4s chains so that all four floating-point units stay busy (4 units x 4 lanes x 2 FLOPs = 32 FLOPs per cycle, about 102 GFLOP/s at 3.2 GHz; measured ). A first version with 12 chains of the form a = y + a * x reached only 64 GFLOP/s: the compiler had to add a register copy before every fmla, because fmla overwrites its accumulator. The bandwidth row reads a 512 MB array once: one core reaches about half of the chip's 200 GB/s, all eight about GB/s (the GPU shares the rest).
The matrix-matrix product is compute-bound (intensity about 85 FLOPs per byte for 512 x 512 matrices read once), yet the simple tiled loop reached only about a quarter of peak: it is limited by loads and stores inside the core, not by DRAM. Libraries close that gap with register blocking (keeping a small tile of the output in registers across the whole inner loop); on the GPU that craft is Topic: cuda-and-gpu-programming.
illustrative An 8-billion-parameter model in 16-bit weights is 16 GB, so at GB/s this laptop's CPU could produce at most about tokens per second however fast its arithmetic; in llama.cpp's 4-bit q4_0 format (18 bytes per 32 weights, 4.5 bits each) it is 4.5 GB and the ceiling rises to about . Weights only: the KV cache and activations add bytes, so real ceilings are lower (Quantization and Precision owns the formats).
Profile before optimising: a sampling profiler records where the program is thousands of times a second (which profiler answers which question is Scheduling and CPU time; flame graphs for services are Capacity planning and performance). For one hot loop the quickest health check is two hardware counters, instructions retired and cycles, and their ratio, instructions per cycle (IPC). macOS's /usr/bin/time -l prints both. The row and column sums of section 2, 20 times each:
The column walk ran 4 times as many instructions (no SIMD) and still spent most cycles waiting: instructions per cycle against . An IPC well below 1 on a loop says "waiting for memory" (or for mispredicted branches); 3 or more says the core is busy computing.
keep(), an empty asm volatile that forces the value to exist (bench.h); Google Benchmark calls it benchmark::DoNotOptimize.-O0 keeps every variable in memory and calls every function; benchmark optimised builds, with debug info (-O2 -g) for profiling.Not run here: Instruments' Time Profiler (xcrun xctrace record --template 'Time Profiler' --launch -- ./prog) hung even for xctrace version, the built-in sample tool could not attach in this session, and Linux's perf record -g, perf report and perf stat (perf wiki) need a Linux machine. Treat those commands as reference.
An API is a contract in source code. An ABI (application binary interface) is the contract between already-compiled machine code: which registers carry arguments (section 5), how structs are laid out (section 3), how virtual tables and exceptions work, and what symbols are called. Two object files work together only if they agree on all of it; Python programmers meet it as "this wheel does not match your Python" or a crash after mixing builds.
Name mangling. C has one function per name; C++ allows the same name in different namespaces and overloads, so the compiler encodes the namespace and parameter types into the symbol, following the Itanium C++ ABI (used by clang and GCC everywhere except Windows, despite its name). extern "C" turns mangling off, which is why every C++ library meant to be called from another language exposes a C interface.
Read __ZN9ggml_like3dotEPKfS1_i as: _Z a mangled name (macOS adds one more underscore), N ... E a nested name of 9ggml_like (9 characters) and 3dot, then the parameters: PKf pointer to const float, S1_ the same type again, i int. The double overload differs only in d; c_dot is just _c_dot.
ctypes and cffi call only C symbols, so they need extern "C". pybind11 and nanobind compile C++ against CPython's own C ABI; a wheel built for one Python version works only on that version unless it uses the limited "abi3" stable ABI (Rust: speeding up Python with PyO3 and maturin covers abi3 wheels).std::string, std::vector and friends have different layouts, so a std::string cannot cross between code built against the two. Within one library, flags that change layouts (debug iterators, _GLIBCXX_USE_CXX11_ABI on Linux) must match.std::unordered_map's node-based buckets, std::regex) stay as they are for that reason.#define, packing pragma or alignment) break the one-definition rule: no error, just corrupted fields at run time.Apple's ARM64 ABI differs from the standard Linux one in a few details (for example, how variadic arguments are passed): Writing ARM64 code for Apple platforms.
Everything above carries over to GPUs: SIMD becomes SIMT (a warp of 32 threads runs one instruction together, written as scalar code per thread), cache lines become coalescing (a warp should read neighbouring addresses), a mispredicted branch becomes divergence (both paths run in turn), and the roofline's ridge moves far right, so LLM decode is even more memory-bound. The owners: The CUDA programming model for threads, warps and divergence, GPU memory hierarchy for coalescing and shared-memory tiling. CUDA C++ is C++ with extensions; this page and the essentials are its prerequisites.
| Idea on the CPU (this page) | Its GPU counterpart |
|---|---|
| A few large cores with big caches, branch predictors and out-of-order execution, built to make one thread fast | Thousands of simple lanes, built for throughput; little cache per lane, no out-of-order execution |
| Latency hidden by caches and the prefetcher | Latency hidden by switching between many groups of threads while some wait for memory |
| SIMD: one instruction on 4 lanes (NEON), written as vectors | SIMT: groups of 32 threads (a warp) run one instruction together, written as scalar code per thread |
| Cache lines: read neighbours together | Coalescing: the threads of a warp should read neighbouring addresses |
| A branch mispredicted costs a pipeline flush | Threads of a warp that take different branches run both paths, one after the other (divergence) |
| Register blocking, cache tiling | Shared-memory tiling, tensor cores |
| Roofline with about 100 GB/s and 0.5 TFLOP/s on this laptop's CPU | The same model at TB/s and hundreds of TFLOP/s: the ridge is further right |
| Atomics and memory orders between threads | The same, plus scopes (block, device, system) |
The build, undefined behaviour and sanitizers, libraries: what this page assumes.
new and delete, RAII, smart pointers and moves, the language side of section 3's allocation.
Virtual dispatch and templates measured: the abstractions whose code section 5 reads.
This page's ideas in a real inference engine: mmap loading, quantised blocks, SIMD kernels, thread barriers.
The roofline, decode and prefill bounds; the CPU roofs measured here plotted beside the M1 GPU and datacenter chips.
The operating-system side of sections 4, 3 and 8: page tables and the TLB, malloc and arenas, locks and futexes.
Where section 12 continues: kernels, GPU memory, tiling.
Floating-point rounding, summation error and why order matters (section 6's 23% error).
Why the interpreter hides all of this, and how to move the loop out of Python.
The root: the languages compared, the shared benchmark.
The classic on caches, TLBs and NUMA; old numbers, lasting ideas. about 4 hours
A free book on exactly this page's subject, with measured examples: SIMD, caches, branchless code. about 10 hours; chapters stand alone
The reference for x86 code generation and microarchitecture (the old page's Stage 3 pick). about 5 hours for the C++ manual
Measured latencies and units of the M1's performance core, used in section 6. reference
The clearest short explanation of memory orders. 15 minutes
Section 5's habit, in the browser. no reading time
The model behind section 9. 45 minutes
The talk that made AoS against SoA mainstream. 1 hour 30 minutes
Why contiguous containers win, from the old page's list of CppCon performance talks. 1 hour 15 minutes
Book: allocation, containers and profiling in practice (the old page's Stage 3 pick). about 9 hours 30 minutes