Sub topic 1
Why memory is slower than the CPU: the memory hierarchy
Prerequisites
This chapter assumes you can read C and are comfortable with arrays, structs, and pointers. You should know Big-O notation. You do not need any hardware background. The numbers below are typical for a desktop or server x86-64 or ARM processor from the last several years. Your machine will differ, and the benchmark later in the chapter lets you measure it.
The gap that drives everything
A modern core can start several instructions per cycle at 3 to 5 GHz. A read from main memory (DRAM, the large memory on the motherboard) takes roughly 60 to 100 nanoseconds. In that time the core could have executed several hundred instructions.
Big-O analysis counts operations and treats every memory access as costing the same. On real hardware that assumption is false. Two loops that do identical work can differ in speed by 10x or more, depending on where their data lives when they ask for it.
Processor speed has grown faster than DRAM latency has shrunk. Hardware designers did not fix this by making DRAM faster. They hid it behind small, fast memories called caches. The rest of this tutorial is about writing code that works with those caches instead of against them.
The hierarchy
Fast memory is expensive and takes physical space close to the core. Large memory is cheap but slow. A hierarchy combines both: each level is smaller and faster than the one below it, and it holds copies of data from the level below.
| Level | Typical size | Typical latency | Scope |
|---|---|---|---|
| Registers | a few hundred bytes | 0 to 1 cycle | one core |
| L1 cache | 32 to 48 KB (data) | about 1 ns (4 to 5 cycles) | one core |
| L2 cache | 256 KB to 2 MB | about 3 to 5 ns | one core, sometimes shared by a few |
| L3 cache | 4 MB to 100+ MB | about 10 to 20 ns | shared by all cores |
| Main memory (DRAM) | gigabytes | about 60 to 100 ns | whole machine |
| SSD | terabytes | tens of microseconds | whole machine |
Each step down costs roughly 3x to 10x in latency. Going from L1 to DRAM costs about 60x to 100x.
How the hierarchy behaves
When the core reads an address, the hardware checks L1 first. If the data is there, that is a hit and the read is fast. If not, it is a miss. The request moves to L2, then L3, then DRAM. The data found at the lower level is copied into the faster levels on the way back, so a second access to the same address is cheap.
This only helps if programs tend to reuse data or use nearby data. They usually do, and that tendency is called locality. The next chapters cover it in detail. For now, remember that the hierarchy is a bet on locality. Code that wins the bet runs near L1 speed. Code that loses it runs near DRAM speed.
Three things to keep in mind:
- The hardware manages the caches. You do not allocate cache space or move data between levels explicitly. You influence the outcome only through how you lay out and access data.
- Average cost depends on hit rate. If L1 hits cost 1 ns and DRAM accesses cost 80 ns, a 95% hit rate averages about 5 ns per access (0.95 × 1 + 0.05 × 80 = 4.95). A 99% hit rate averages about 1.8 ns. A few percentage points of hit rate change runtime a lot.
- Cores share the lower levels. L3 and DRAM bandwidth are shared. Other threads or processes can evict your data or consume bandwidth.
Seeing the hierarchy in a benchmark
The program below measures the cost of one dependent memory read as the working set grows. It builds a random cycle through a buffer and follows it. Each load depends on the previous one, so the CPU cannot overlap them. The random order defeats the hardware's attempts to guess the next address.
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
static double now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1e9 + ts.tv_nsec;
}
/* Returns average nanoseconds per dependent load over a working set of n slots. */
static double chase(size_t n, size_t steps) {
size_t *next = malloc(n * sizeof *next);
size_t *perm = malloc(n * sizeof *perm);
if (!next || !perm) exit(1);
for (size_t i = 0; i < n; i++) perm[i] = i;
for (size_t i = n - 1; i > 0; i--) { /* Fisher-Yates shuffle */
size_t j = (size_t)rand() % (i + 1);
size_t t = perm[i]; perm[i] = perm[j]; perm[j] = t;
}
/* Link the shuffled order into a single cycle that visits every slot. */
for (size_t i = 0; i < n; i++) next[perm[i]] = perm[(i + 1) % n];
size_t p = perm[0];
double t0 = now_ns();
for (size_t s = 0; s < steps; s++) p = next[p];
double t1 = now_ns();
volatile size_t sink = p; /* keep the loop from being optimized away */
(void)sink;
free(next);
free(perm);
return (t1 - t0) / (double)steps;
}
int main(void) {
for (size_t kb = 4; kb <= 256 * 1024; kb *= 4) {
size_t n = kb * 1024 / sizeof(size_t);
printf("%8zu KB: %6.2f ns per load\n", kb, chase(n, 20000000));
}
return 0;
}Compile it with gcc -O2 chase.c -o chase on Linux or macOS and run it on an otherwise idle machine. You should see a staircase. Small sizes sit near 1 ns. Latency rises when the buffer exceeds L1, rises again past L2, again past L3, and settles at DRAM latency for the largest sizes. The steps show you the cache sizes of your own CPU.
Common misconceptions
- "Fewer instructions means faster code." Not when the instructions wait on memory. A loop with twice the instructions but sequential access can beat a leaner loop that misses cache on every iteration.
- "Big-O tells me which structure is faster." It describes growth, not constant factors. An O(n) scan of a small contiguous array often beats an O(log n) search through scattered nodes, because the constant factor is dominated by misses.
- "More RAM makes my program faster." Capacity does not change latency. A program whose working set fits in L2 can be several times faster than the same program whose working set is spread across DRAM.
What comes next
The hierarchy explains why locality matters. The next chapter looks at how data moves between levels: in fixed-size blocks called cache lines, not single bytes. That detail determines which layouts and traversal orders are cheap.
Exercise
A program has an L1 hit latency of 1 ns and a DRAM latency of 80 ns. Ignore L2 and L3. By how much does the average access time change if the L1 hit rate improves from 90% to 98%?
Show answer
At 90% the average is 0.9 × 1 + 0.1 × 80 = 8.9 ns. At 98% it is 0.98 × 1 + 0.02 × 80 = 2.58 ns. The average drops by about 6.3 ns, a speedup of roughly 3.4x on memory time, even though the hit rate rose by only 8 percentage points.
Exercise
In the pointer-chasing benchmark, why would the measured latency at large sizes look much lower if the cycle visited slots in sequential order (slot 0, 1, 2, ...) instead of a random order?
Show answer
With a sequential order, neighboring slots share cache lines, so most loads hit data already fetched, and the hardware prefetcher can detect the pattern and fetch ahead. The benchmark would then measure throughput of sequential access, not the latency of reaching DRAM. The random order removes both effects.