C++: the machine underneath: caches, layout, SIMD and the memory model

What the processor and memory do with compiled code: the cache ladder, cache lines and data layout, assembly, SIMD, branch prediction, atomics and memory order, the CPU's measured roofline and the ABI. Every number measured on an Apple M1 Pro by small C++ programs you can read in full. Reading: 33 min, plus 21 in closed details. Data as of October 2026.
The idea in one sentenceOnce a loop compiles to a handful of machine instructions, memory, not arithmetic, sets its speed: where the data sits in the cache ladder, how it is laid out in cache lines and whether the compiler could turn it into independent SIMD work decide whether the same loop runs 50 times faster or slower.

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.

Cache line: the unit memory moves in, 128 bytes on Apple silicon (64 on most x86).
Prefetcher: hardware that spots a regular address pattern and fetches lines before they are asked for.
AoS / SoA: array of structs (records side by side) / struct of arrays (one array per field).
SIMD, NEON: one instruction on a short vector (4 floats in a 128-bit NEON register on ARM).
Dependency chain: instructions that each wait for the previous result; its length, not the instruction count, sets the time.
Misprediction: the core guessed a branch wrong and throws away the work it did on the guess.
Memory order: what an atomic operation promises about the order other cores see writes in (relaxed, acquire, release, seq_cst).
False sharing: two threads writing different variables on one cache line, fighting over the line.
ABI: the binary contract between compiled pieces: registers, layouts, symbol names.

One load from DRAM costs as much time as 13,000 floating-point operations

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.

In one screen

Each row: one idea, the number that shows it on this M1 Pro, and what it changes in the code you write.

IdeaMeasured on this M1 ProWhat to do
Memory is a ladder of cachesA load takes ns from L1 and about ns from DRAM when the address is unpredictableKeep the working set small; reuse data while it is hot
Memory moves in 128-byte linesSumming a matrix by columns is x slower than by rowsWalk memory in the order it is laid out
Layout decides what you readStruct of arrays is x faster than array of structs for one field of eightGroup the fields that are used together; values, not pointers
Memory comes in 16 KB pages, lazilyA first touch costs about microseconds per pagemmap big read-only files
The compiler rewrites your codeAt -O2 a loop of n calls became a formula with no loopRead the assembly before guessing
SIMD: one instruction, four floatsDot product: x faster with NEON and independent accumulatorsBreak dependency chains; let the compiler vectorise
The processor guesses branchesUnpredictable branch: x slower than the same loop on sorted dataMake branches predictable or remove them
Cores see memory in different ordersRelaxed atomics: reordered messages in 52 million; false sharing: x slowerRelease/acquire to publish data; one 128-byte line per hot counter
Most code is memory-boundMatrix-vector product: GFLOP/s of a GFLOP/s coreCount bytes, not FLOPs, for LLM decode
Measure, with countersColumn walk: instructions per cycle against Profile first; microbenchmarks mislead
The ABI is a binary contractdot(const float*, ...) is the symbol __ZN9ggml_like3dotEPKfS1_iextern "C" at language boundaries
How everything on this page was measured

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/.

Why Python never showed you this
In CPython, 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.

1. The ladder of caches

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).

  1. Five levels, one core's view. Registers inside the core, then L1, L2, the system level cache (SLC) and DRAM, each plate as wide as the logarithm of its size. Every level holds copies of lines from the one below.
  2. A hit in L1. The value is already in L1 and goes straight to a register: ns per load over a 16 KB buffer, about three clock cycles.
  3. A miss in L1, a hit in L2. L1 fetches the whole 128-byte line that holds the value from L2, keeps it, and hands the value up: ns over a 1 MB buffer, about six times L1.
  4. A miss all the way to DRAM. The line comes up through every level and each keeps a copy: ns over a 512 MB buffer read in random order, more than a hundred times L1.
  5. A pointer chase waits for every trip. To time one load you must stop the processor from overlapping loads. A pointer chase does it: a linked list scattered over a buffer, each node holding the address of the next, so load k+1 cannot start before load k returns. Time per load is the latency of whatever level holds the buffer.
  6. Address order: the prefetcher runs ahead. The same 512 MB, but the list visits the nodes in address order: ns per load against ns, although each load still waits for the previous one. The prefetcher notices that addresses go up by 128 bytes each time and fetches the next lines before they are asked for. Predictable access is the cheapest optimisation there is: you get it by storing data in the order you read it.

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.

Each time the buffer outgrows a cache, a load gets several times dearer

Hover or tap the chart to read any point.

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.

The measured ladder

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:

  1. 4 KB to 128 KB: L1. Up to 128 KB (L1) a load costs about 1 ns, three clock cycles: to ns, flat.
  2. 192 KB to 6 MB: L2. Past that the buffer lives in L2 and loads cost 5 to 15 ns: ns at 192 KB, ns at 6 MB.
  3. 8 MB to 48 MB: the climb. From about 8 MB they climb towards DRAM's roughly 125 ns: ns at 8 MB, at 16 MB, at 48 MB. The L2 is shared with other programs, and the system level cache sits between L2 and DRAM and shows only as a softer ramp.
  4. 64 MB to 1 GB: DRAM, a hundred times L1. to ns. It still creeps up because past a few MB the chase also misses in the TLB, the cache of address translations (Virtual memory owns it).
  5. Three runs, soft steps. The other two random-order runs, drawn faintly, agree within about 8% at every size except from 2 MB to 16 MB, where they spread by up to 53% (at 6 MB). The steps are soft because other programs share L2 and DRAM.
  6. Address order. The dashed curves: the same buffers visited in address order cost under 2 ns up to 6 MB and 10.8 to 14.2 ns from 64 MB to 1 GB (both runs), about a tenth of the random order, because the prefetcher fetches ahead.

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.

In Python
A Python list of floats is an array of pointers to float objects scattered on the heap, so iterating it is closer to a pointer chase than to a scan; the root page measured about 17 ns per element in order and 77 ns shuffled. A NumPy array stores the numbers themselves, contiguously.
The pointer chase in code, the sysctl output and the table of all sizes

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):

By columns, every element costs a whole line and the cache forgets it before it is reused

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.

2. Cache lines: use what you fetched

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.

  1. Rows: the first element. Adding element 0 misses: the whole line L0 (128 bytes) comes in to use 4 of them.
  2. Rows: the rest of the line is free. The next 31 elements are in the same line: 32 additions, 1 line fetched, all 128 bytes used.
  3. Rows: the whole matrix. 16 lines fetched for 512 additions: 2,048 bytes moved, 2,048 used, 100%.
  4. Columns: every element is a new line. Down column 0 each element sits in the next row's line, 128 bytes further on: 8 additions, 8 lines fetched, 32 of 1,024 bytes used. The 8-line cache is now full.
  5. Columns: the cache starts forgetting. Rows 8 to 15 of column 0 evict lines L0 to L7, the least recently used: 16 lines fetched for 16 additions.
  6. Columns: back at the top, the line is gone. Column 1 needs L0 again, but it was evicted; all 16 miss again: 32 lines fetched for 32 additions.
  7. Columns: the whole matrix. 512 lines fetched for 512 additions: 65,536 bytes moved to use 2,048, 3%, 32 times the traffic of row order. The real program, measured, is x slower by columns.

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.

The program (rowcol.cpp) and its recorded output
In NumPy and PyTorch
a.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.

3. Data layout: padding, AoS and SoA

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?

Array of structs against struct of arrays

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.

  1. One record, 32 bytes. A 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.
  2. AoS: one field pulls whole lines. Summing user touches every line: 8 lines fetched, 1,024 bytes moved to use 128, 4 of every 32 bytes (12.5%).
  3. SoA: one array per field. The same 32 records rearranged as 8 arrays, one per field, each exactly one line here. Summing user fetches 1 line and uses all 128 bytes; the other 7 arrays are never touched.
  4. Measured: about 8 times faster. Over 20 million records the integer field took ns per record as AoS against ns as SoA, x: the ratio of bytes read (32 against 4). Both loops stream at roughly 50 GB/s; SoA has 8 times fewer bytes to stream.
  5. All eight fields: about 1.2x. When the loop uses every field, AoS uses every byte it fetches too: against ns per record.

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:

  • Integer field: ns against ns per record over three runs, about 8x, the ratio of bytes read (32 against 4). Both loops stream at roughly 50 GB/s; SoA has 8 times fewer bytes to stream.
  • Float field: no difference. Both take about 1 ns per record, limited by something else: the C++ standard makes 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.
  • All 8 fields: AoS only about 1.2x slower, since it uses every byte it reads.
The program (aos_soa.cpp) and its recorded output
Correction to the old page
"C++: zero to expert" said array-of-structs versus struct-of-arrays "changes throughput by an order of magnitude". Measured here, the gain is the ratio of bytes read to bytes used, and only when memory is the bottleneck: about 8x for one field of a 32-byte record, about 1.2x when all fields are used, nothing when a chain of dependent float additions is the limit. A 64- or 128-byte record would give more than 10x for one field. Measure your own access pattern.

A 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.

The allocation measurement: growth, reserve, heap objects, small strings


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).

4. Pages and mmap, as a C++ program meets them

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).

The mmap measurement, three runs (cold and warm page cache), and llama.cpp's loader


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.

5. The compiler's view: reading assembly

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:

  • Inlining: copying a small function's body into its caller, removing the call and letting the optimiser see through it. It is why small functions, lambdas and templates cost nothing, and it needs the body to be visible: same file, a header, or link-time optimisation (-flto).
  • Devirtualisation: a 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.)
  • Vectorisation: processing several elements per instruction (next section). Clang reports its decisions with -Rpass=loop-vectorize (done), -Rpass-missed=loop-vectorize (refused) and -Rpass-analysis=loop-vectorize (why) (LLVM vectoriser docs).
Devirtualisation in the assembly: a virtual call against a final class

area_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:


A report is not the truth
The remark says 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.
ARM64 assembly in two minutes: registers, the calling convention, the instructions you will meet

This laptop runs ARM64 (AArch64). Each line is one instruction, written operation destination, source, source:

You seeIt means
x0 .. x30, w0 .. w30The 64-bit general registers; w is the low 32 bits of the same register. sp is the stack pointer.
s0, d0, q0, v0.4sThe 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 resultBy 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, ldpLoad 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, fmlaInteger 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, tbzCompare (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, retCall a function, jump to an address held in a register, return.

6. SIMD: one instruction, several numbers

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).

16 products, three schedules: lanes across, cycles down

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.

Why: dependency chains, not instruction counts

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.

  1. One block of 16 products. One 16-element block of the benchmark's own inputs (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).
  2. Scalar: one chain of 16 fmadd. Each one adds into s0, so it waits 4 cycles for the previous one: 64 cycles for the block, 4 per element.
  3. -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.
  4. NEON, 4 accumulators. Four fmla.4s, one per register v0..v3, each doing 4 multiply-adds: all 16 in 4 cycles, 0.25 cycles per element.
  5. The reduction, once per loop. 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.
  6. Predicted against measured. 4, 3 and 0.25 cycles per element at 3.2 GHz predict 1.25, 0.94 and 0.078 ns per element; measured in L1: , and ns.

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):

Fast-math changed the answer

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.

In NumPy
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 real assembly of the four loops, and the same design in llama.cpp

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.

7. Branch prediction

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:

The program (branch.cpp)

Predict. Compiled normally at -O2: how much faster is the sorted run?

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.

8. Atomics and the C++ memory model

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):

OrderIn plain wordsARM64 code (real)
relaxedThis 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.

  1. Two threads, two variables. Thread A, on one core, will store data = 1 then flag = 1; thread B, on another, loads flag then data. Both start at 0 in the shared caches.
  2. Stores wait in a store buffer. A's two stores go into its private store buffer in program order. Until they drain into the shared cache, no other core can see them.
  3. Relaxed: nothing orders the drain. Plain str instructions promise nothing about which store becomes visible first: here flag = 1 reaches the shared cache while data = 1 still waits.
  4. B sees the flag but not the data. B loads 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.
  5. Release: 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.
  6. Acquire: 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.

The program (litmus.cpp) and its recorded output

Plain 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.

The code each memory order compiles to, the race program, its 300 runs and ThreadSanitizer's report

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):


False sharing

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:

  1. One thread alone. Its counter's line stays in its own core's L1: 100 million increments in ms.
  2. Four counters 8 bytes apart. All four sit in one 128-byte line. Before a core writes, every other core's copy is invalidated, so the line travels from core to core on almost every increment: ms, times one thread alone, although no data is shared.
  3. 64 bytes apart. Two counters per 128-byte line, so two lines, each fought over by two cores: ms.
  4. 128 bytes apart. One line each, no fight: ms, about the time of one thread alone.

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:


ggml-cpu/ops.h L8-18.

The program (false_sharing.cpp) and its recorded output

On 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.

9. The CPU's roofline, measured

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).

How the peak was reached, why the matrix-matrix product stays at a quarter of it, and the decode ceilings on this laptop


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).

10. Measuring: counters, and why microbenchmarks lie

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.

Why microbenchmarks lie, and the profilers not run here

  • The compiler deletes unused work. If a result is never used, the loop may vanish. Every benchmark here passes results to keep(), an empty asm volatile that forces the value to exist (bench.h); Google Benchmark calls it benchmark::DoNotOptimize.
  • Caches are warm. A loop timed a million times on the same few KB runs from L1; the same code in a real program meets cold data. The NEON dot product ran about twice as fast in L1 as from DRAM, and a load from DRAM costs 100 times one from L1 (section 1).
  • The compiler sees your test data. A constant input can be folded away (section 5's formula).
  • A debug build means nothing. -O0 keeps every variable in memory and calls every function; benchmark optimised builds, with debug info (-O2 -g) for profiling.
  • Cores differ and clocks move. This chip has fast and slow cores; macOS cannot pin a thread to a core, so the benchmarks ask for the highest quality-of-service class and report the best of several runs.
  • The machine is busy. Every timing on this page says how many runs it took and how far they spread, and records the load average. Multi-threaded results spread most.

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.

11. The ABI: C++'s binary contract

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.

From Python
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).
What breaks when you mix builds
  • Different standard libraries. clang on macOS uses libc++; GCC on Linux uses libstdc++. Their 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.
  • Standard library designs that cannot be fixed. Programs compiled years ago still link against today's shared standard library, so vendors avoid any change to a type's layout or a function's mangled name; known-slow designs (std::unordered_map's node-based buckets, std::regex) stay as they are for that reason.
  • Headers and flags out of step. Two translation units that see different definitions of the same struct (a different #define, packing pragma or alignment) break the one-definition rule: no error, just corrupted fields at run time.
  • Mixing compilers is fine through a C interface, risky through C++ types, and the reason C++ has no universal package of prebuilt binaries like PyPI's wheels (builds and package managers are on C++: the essentials).

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.

12. To the GPU: the same ideas with the dials turned

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.

The mapping, row by row
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 fastThousands of simple lanes, built for throughput; little cache per lane, no out-of-order execution
Latency hidden by caches and the prefetcherLatency hidden by switching between many groups of threads while some wait for memory
SIMD: one instruction on 4 lanes (NEON), written as vectorsSIMT: groups of 32 threads (a warp) run one instruction together, written as scalar code per thread
Cache lines: read neighbours togetherCoalescing: the threads of a warp should read neighbouring addresses
A branch mispredicted costs a pipeline flushThreads of a warp that take different branches run both paths, one after the other (divergence)
Register blocking, cache tilingShared-memory tiling, tensor cores
Roofline with about 100 GB/s and 0.5 TFLOP/s on this laptop's CPUThe same model at TB/s and hundreds of TFLOP/s: the ridge is further right
Atomics and memory orders between threadsThe same, plus scopes (block, device, system)