โ† Back to Home

๐Ÿ–ฅ๏ธ How Computers Actually Run Your Code

Pipelines, branch prediction, caches and SIMD: why two O(n) loops over the same data can differ in speed by 25ร—.

Big-O tells you how work grows. It doesn't tell you why two O(n) loops over the same data can differ in speed by 25ร—. That gap comes from the hardware: how the CPU executes instructions, how it guesses which way your code will go, and above all how it gets data from memory.

You don't need to write assembly to benefit from this. A rough model of the machine is enough to explain most "mysterious" performance results.

The CPU in one paragraph

A CPU core repeatedly fetches an instruction, decodes it, executes it, and writes back the result. It works on a small set of registers, about 16 general-purpose ones on x86-64, which are the only storage it can compute on directly. Everything else has to be loaded from memory first. A 3โ€“5 GHz clock means a core gets a few billion cycles per second, and a modern core can finish several instructions per cycle.

That only works if the core is kept fed with instructions and data, and doing so is most of what modern CPU design is about.

Pipelining and out-of-order execution

Doing one instruction start to finish before beginning the next would leave most of the chip idle. Instead, CPUs pipeline like an assembly line: while one instruction executes, the next is being decoded and the one after that fetched. Modern cores go further. They look ahead across hundreds of instructions, run the independent ones out of order and in parallel, and then commit results in the original order so the program can't tell.

So the CPU is effectively running ahead of your code. That's great, until it doesn't know which way the code goes next.

Branch prediction

At every if, the pipeline would have to stall until the condition is known. Instead, the CPU predicts the outcome and keeps executing speculatively. A correct guess costs nothing. A wrong guess means throwing away the speculative work and restarting, which costs around 15โ€“20 cycles.

Predictors are very good at patterns ("this branch is almost always taken") and helpless against randomness. Here's a classic experiment:

/* branch.c: sum values >= 128 from 16M random bytes, 10 times */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N (1 << 24)

static int cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b; }

static double run(const int *data) {
    struct timespec t0, t1;
    clock_gettime(CLOCK_MONOTONIC, &t0);
    long sum = 0;
    for (int rep = 0; rep < 10; rep++)
        for (int i = 0; i < N; i++)
            if (data[i] >= 128)                 /* the branch the CPU must predict */
                sum += data[i];
    clock_gettime(CLOCK_MONOTONIC, &t1);
    if (sum == 42) puts("");                    /* keep sum alive */
    return (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
}

int main(void) {
    int *data = malloc(sizeof(int) * N);
    srand(1);
    for (int i = 0; i < N; i++) data[i] = rand() % 256;
    double unsorted = run(data);
    qsort(data, N, sizeof(int), cmp);
    double sorted = run(data);
    printf("unsorted: %.3f s   sorted: %.3f s   (%.1fx faster when sorted)\n",
           unsorted, sorted, unsorted / sorted);
    free(data);
    return 0;
}

Same data, same number of additions. Only the order differs. Results on an AMD Ryzen 7 5800H:

Build Unsorted Sorted
gcc -O2 -fno-if-conversion -fno-if-conversion2 -fno-tree-vectorize (real branch) 0.54 s 0.07 s, 7.5ร— faster
gcc -O2 (default) 0.09 s 0.09 s, no difference

With a real branch, random data makes the predictor wrong about half the time, and the loop runs 7.5ร— slower. Once the data is sorted, the branch goes "no" for a long stretch and then "yes" for the rest, which the predictor learns almost instantly.

The second row is the other half of the lesson. With default optimizations, GCC removed the branch entirely, replacing it with a branch-free conditional move. With no branch, there's nothing to mispredict. When a hot loop has an unpredictable condition, compilers, and sometimes you, can turn control flow into arithmetic.

Branch prediction also has a dark side. Spectre (2018) showed that speculative execution leaves traces in the cache that an attacker can measure to read memory they shouldn't access. Many of the kernel and browser mitigations since then exist because of it.

The memory hierarchy

This is the most important part. A CPU can do an addition in under a nanosecond, but fetching a value from main memory takes around 100 ns, long enough for hundreds of instructions. To hide that, CPUs keep a hierarchy of caches:

Level Typical size (per core / shared) Typical latency In human terms (if 1 cycle = 1 second)
Register ~1 KiB ~0.3 ns 1 second
L1 cache 32โ€“64 KiB per core ~1 ns 4 seconds
L2 cache 512 KiB โ€“ 2 MiB per core ~3โ€“5 ns 15 seconds
L3 cache 16โ€“64 MiB shared ~10โ€“40 ns 1โ€“2 minutes
Main memory (DRAM) GBs ~80โ€“120 ns 5โ€“6 minutes
NVMe SSD random read TBs ~20โ€“100 ยตs 1โ€“4 days
Network round trip, same data center โ€“ ~0.5 ms 2โ€“3 weeks
Network round trip, Europe โ†” US โ€“ ~80โ€“150 ms 8โ€“15 years

Exact numbers vary by chip, but the ratios hold: each level is several times slower than the one above it, and going to the network is millions of times slower than a register. That's why caching, batching and avoiding round trips matter so much in system design.

Cache lines and locality

Memory moves between RAM and cache in cache lines of 64 bytes, not single bytes. Reading one 4-byte integer brings the next 15 along with it. CPUs also detect sequential access and prefetch the following lines before you ask for them.

So code that touches memory in order (spatial locality) and reuses recently touched data (temporal locality) runs far faster than code that jumps around. This experiment sums the same 64 MiB matrix twice:

/* locality.c: same work, different memory access order */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 4096

static double now(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

int main(void) {
    int *m = malloc(sizeof(int) * N * N);      /* 4096 x 4096 ints = 64 MiB */
    for (long i = 0; i < (long)N * N; i++) m[i] = 1;

    double t0 = now();
    long sum = 0;
    for (int r = 0; r < N; r++)                /* row by row: walks memory in order */
        for (int c = 0; c < N; c++)
            sum += m[r * N + c];
    double rows = now() - t0;

    t0 = now();
    for (int c = 0; c < N; c++)                /* column by column: jumps 16 KiB each step */
        for (int r = 0; r < N; r++)
            sum += m[r * N + c];
    double cols = now() - t0;

    printf("row-major: %.3f s   column-major: %.3f s   (%.1fx slower)  sum=%ld\n",
           rows, cols, cols / rows, sum);
    free(m);
    return 0;
}

On the same Ryzen laptop, compiled with gcc -O2, the column-by-column loop is about 25ร— slower. Row-major order lets the compiler also use SIMD instructions (below). With vectorization disabled (-O1 -fno-tree-vectorize), the gap from cache behavior alone is still about 11ร—.

The same principle shows up at every level of the stack:

False sharing

Caches are kept coherent across cores at the granularity of cache lines. If two threads on different cores write to different variables that happen to share a 64-byte line, the line bounces between cores on every write, and both threads slow down dramatically even though they never touch each other's data. This is called false sharing. The fix is padding or aligning hot per-thread counters onto separate lines; Java's @Contended and Go's cpu.CacheLinePad exist for this.

SIMD: one instruction, many values

Modern CPUs have vector registers (128โ€“512 bits wide) that apply one instruction to several values at once. With AVX2, one instruction can add eight 32-bit integers. Compilers vectorize simple loops automatically, which is part of why the row-major loop above was so fast. Libraries such as NumPy, simdjson and every serious video codec rely on SIMD heavily.

import time
import numpy as np

data = list(range(10_000_000))
arr = np.arange(10_000_000, dtype=np.int64)

t0 = time.perf_counter(); s1 = sum(data);  t1 = time.perf_counter()
s2 = int(arr.sum());                       t2 = time.perf_counter()
assert s1 == s2
print(f"Python sum: {t1 - t0:.3f}s   NumPy sum: {t2 - t1:.4f}s")
# NumPy is typically 10-50x faster: contiguous memory, no per-item objects, SIMD

Multiple cores

Clock speeds stopped rising around 2005, at roughly 3โ€“5 GHz, because of power and heat limits. Since then, chips have added more cores instead. That's why concurrency stopped being optional, and why a single-threaded program uses only a fraction of a modern machine. Concurrency Fundamentals covers how to use those cores safely.

What to take away

You rarely need to tune at this level, but a few habits come straight from it:

  1. Access memory sequentially when you can. Contiguous arrays and columnar layouts beat pointer-chasing.
  2. Keep hot data small, so it fits in cache.
  3. Avoid unpredictable branches in hot loops, or let the compiler make them branch-free.
  4. Batch work to amortize slow operations: one network call with 100 items beats 100 calls.
  5. Measure. Use perf stat, which reports cache misses and branch mispredictions, and flame graphs before guessing.

The machine is fast when you go with its grain. Most of the time, that means keeping data close together and predictable.

Copied to clipboard!