Memory Hierarchy: Registers to Storage
Understanding the memory hierarchy from registers to storage drives — speed vs capacity trade-offs, cache behavior, and why locality determines performance.
Understanding the memory hierarchy from registers to storage drives — speed vs capacity trade-offs, cache behavior, and why locality determines performance.
Memory Hierarchy: Registers to Storage
A program can reuse data from a nearby cache, fetch it from DRAM, or wait for a storage device. Those paths differ in capacity, latency, and bandwidth. The differences explain why data layout and access patterns can matter as much as instruction count.
The figures below are examples tied to named Intel desktop processors and Intel’s optimization guidance. They are not timing guarantees for other CPUs. For SSDs and hard drives, use the exact device model and a workload-specific measurement; a generic latency number hides too much variation.
When this model helps
Use the hierarchy model when profiling shows an application waits on data or when a workload’s working set changes. It helps explain why a sequential scan can behave differently from a pointer-heavy walk, why a larger cache may not help when accesses are scattered, and why storage I/O must be measured separately from DRAM access.
The model is less useful as a lookup table of fixed timings. Cache sharing, prefetching, memory placement, and device queues make real measurements depend on the exact machine and access pattern.
Architecture or Flow Diagram
flowchart TD
REG["Registers"] --> L1["Per-core L1 cache"]
L1 --> L2["L2 cache"]
L2 --> LLC["Last-level cache"]
LLC --> DRAM["Main memory (DRAM)"]
DRAM --> SSD["Persistent storage (SSD / HDD)"]
This is a teaching model. Real processors may have separate instruction and data caches, multiple core types, shared cache slices, and other details that do not fit in a simple ladder.
What the hierarchy describes
A processor executes instructions using architectural state such as registers. Some instruction sets can name memory operands directly; others use explicit load and store instructions. The actual execution units, register renaming, caches, and pipelines are microarchitectural details, so it is misleading to say that every arithmetic operation follows one universal register path.
Caches keep copies of data close to cores. L1 is small and private to a core, L2 is larger, and the last-level cache may be shared. DRAM holds more data but a dependent load takes longer than a cache hit. SSDs and hard drives provide persistent storage through operating-system and device queues; their latency depends on the device and request pattern.
One hardware reference, not a universal chart
Intel lists the Core i7-12700 with 12 MB total L2 and 25 MB Intel Smart Cache. Intel’s Core Ultra 7 265K lists 36 MB total L2 and 30 MB Smart Cache. These two product specifications give a concrete example range for those processor families; they do not define cache sizes for other CPUs.
Intel’s optimization reference manual gives example dependent-load estimates of about 5 cycles for an L1 data-cache hit, 12 for L2, 26 for an L3 hit, and 200 for a memory access. The manual cautions that actual cost varies with memory parameters and concurrent traffic. These cycle estimates are useful for reasoning about one Intel context, not promises for every model or workload.
| Reference | Published example | How to read it |
|---|---|---|
| Intel Core i7-12700 | 12 MB total L2; 25 MB Smart Cache | Product capacity for this SKU |
| Intel Core Ultra 7 265K | 36 MB total L2; 30 MB Smart Cache | Product capacity for this SKU |
| Intel optimization guidance | L1 about 5 cycles, L2 about 12, L3 about 26, DRAM about 200 for its example estimates | Dependent-load estimates; measure the target CPU |
| Core i7-12700 memory support | Up to DDR5-4800, two channels, and 76.8 GB/s listed maximum bandwidth | A platform ceiling; installed memory and workload can lower throughput |
| SSD / HDD | Check the exact model’s capacity and datasheet; measure the application’s read/write pattern | Queue depth, firmware, interface, filesystem, and request size all affect results |
Sources: Intel Core i7-12700 specifications, Intel Core Ultra 7 265K specifications, and the Intel 64 and IA-32 Architectures Optimization Reference Manual.
A cache miss is not automatically one full memory-latency stall. Out-of-order processors can overlap independent loads, and prefetchers may bring data in before the program asks for it. A linked-list walk with dependent pointers exposes latency more directly than a streaming loop. A streaming loop is often limited by bandwidth instead.
Locality and cache lines
Temporal locality means recently used data may be used again. Spatial locality means nearby addresses may be used soon. Caches transfer data in cache lines; 64 bytes is common on contemporary x86 systems, but check the target CPU rather than treating that size as universal.
For an array of adjacent values, one fetched line can serve several nearby accesses. A stride that skips most values uses less of each fetched line and touches a larger address range for the same number of loads. Once the working set grows beyond a cache, more accesses are served by the next level. That transition is gradual and workload-dependent, not a sharp universal boundary.
Latency versus bandwidth
Latency is the delay before a particular request completes. Bandwidth is the amount of data transferred per unit of time. A dependent pointer chain can have low bandwidth because each next address is unknown until the previous load completes. A streaming loop can have high bandwidth because many cache lines are in flight at once.
DRAM transfer rate is often published in MT/s, while peak bandwidth depends on channel count and bus width. For the i7-12700, Intel lists support up to DDR5-4800 and a maximum memory bandwidth of 76.8 GB/s. That is a specification ceiling for a supported configuration, not an expected result for every system.
From DRAM to persistent storage
DRAM is volatile working memory. SSDs and hard drives retain data without power, but their behavior depends on the device and access pattern. Sequential reads, small random reads, queue depth, and write durability can produce very different measurements on the same drive. NAND flash also uses a flash translation layer to map logical block addresses to physical flash; the controller handles erase blocks, wear management, and background work.
Use the drive maker’s datasheet for capacity and rated transfer figures. Then benchmark the real application path. fio can help characterize block-device behavior, but its result is not the same as application latency through a filesystem, database, or network stack.
| Layer | Typical role | What to measure |
|---|---|---|
| Registers | Operands and intermediate values used by instructions | Generated instructions and dependency chains |
| Caches | Copies of recently or nearby accessed data | Working-set size, cache misses, and sharing between cores |
| DRAM | Volatile working data with more capacity than on-chip caches | Dependent-load latency and streaming bandwidth separately |
| SSD / HDD | Persistent data accessed through an I/O stack | Device model, request size, queue depth, read/write mix, and end-to-end latency |
The table compares roles, not speed rankings. Use the hardware-specific references above for processor examples and the actual storage model for device figures.
Production Failure Scenarios
Cache pressure from a larger working set
An application that used to reuse a small set of records may slow down after a feature adds more state. The new working set can exceed one or more cache levels, so the processor fetches data from farther away more often. A single average cache-miss counter will not explain the cause by itself; compare it with profiles, access patterns, and the workload’s size.
Investigation: Measure before and after with the same input. Check whether the hot data became larger, whether the access order changed, and whether concurrent threads now compete for shared cache capacity.
False sharing between threads
Two threads can update different variables that happen to occupy the same cache line. The variables are logically separate, but the coherence protocol tracks ownership at line granularity. This can move a line between cores repeatedly and limit throughput.
Investigation: Profile a multithreaded run and inspect the layout of frequently written fields. Padding or separating hot counters may help, but it also increases memory use. Verify the change on the target architecture.
Storage benchmark does not match production traffic
A sequential read test may look healthy while an application issues small random requests, waits for durable writes, or shares a busy device. Datasheet maximum throughput and synthetic results do not capture those conditions.
Investigation: Record request size, read/write mix, queue depth, filesystem, and durability settings. Measure at the application boundary as well as the block device.
A small array benchmark
This C example performs the same number of loads with sequential and strided access. The strided pass touches a wider address range, so it demonstrates both cache-line use and working-set size. It reports measurements from the machine running it; no result is assumed in advance.
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LOADS (1u << 16)
#define REPEATS 7
#define STRIDE 8
static double seconds(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (double)t.tv_sec + (double)t.tv_nsec / 1e9;
}
static uint64_t scan(const uint64_t *values, size_t loads, size_t stride)
{
uint64_t sum = 0;
for (size_t i = 0; i < loads; ++i)
sum += values[i * stride];
return sum;
}
static double measure(const uint64_t *values, size_t loads, size_t stride,
uint64_t *checksum)
{
double start = seconds();
*checksum += scan(values, loads, stride);
return seconds() - start;
}
int main(void)
{
size_t count = (size_t)LOADS * STRIDE;
uint64_t *values = malloc(count * sizeof(*values));
if (values == NULL)
return 1;
for (size_t i = 0; i < count; ++i)
values[i] = (uint64_t)i;
uint64_t checksum = 0;
for (int warmup = 0; warmup < 2; ++warmup) {
(void)scan(values, LOADS, 1);
(void)scan(values, LOADS, STRIDE);
}
for (int repeat = 0; repeat < REPEATS; ++repeat) {
double sequential = measure(values, LOADS, 1, &checksum);
double strided = measure(values, LOADS, STRIDE, &checksum);
printf("run %d: sequential %.3f ns/load, stride-%d %.3f ns/load\n",
repeat + 1,
sequential * 1e9 / LOADS,
STRIDE,
strided * 1e9 / LOADS);
}
printf("checksum: %" PRIu64 "\n", checksum);
free(values);
return 0;
}
Build with cc -O2 -Wall -Wextra memory-bench.c -o memory-bench and run it several times. To see working-set effects, change LOADS and compare the array size with cache capacities reported by the target machine. The code intentionally uses a larger address span for the strided pass; it does not isolate cache latency from all other effects.
For a useful comparison:
- Run the benchmark when the machine is otherwise idle and repeat it; compare medians, not one run.
- Record CPU model, memory configuration, compiler, and build flags.
- Try working sets below and above the target CPU’s cache capacities.
- Use
perf statcache counters where the processor supports them, and treat event names as CPU-specific. - Expect clock scaling, cache sharing, thermal state, and background processes to add noise.
Inspect cache sizes on Linux
Linux exposes cache information for each CPU through sysfs. The values below describe the running machine; they should not be copied into a general hardware table.
from pathlib import Path
def size_in_bytes(value: str) -> int:
suffix = value[-1].upper()
number = int(value[:-1])
scale = {"K": 1024, "M": 1024**2, "G": 1024**3}.get(suffix, 1)
return number * scale
cache_root = Path("/sys/devices/system/cpu/cpu0/cache")
for index in sorted(cache_root.glob("index*"), key=lambda path: int(path.name[5:])):
level = (index / "level").read_text().strip()
kind = (index / "type").read_text().strip()
size = size_in_bytes((index / "size").read_text().strip())
print(f"L{level} {kind}: {size:,} bytes")
Some systems expose shared caches under more than one CPU directory. Check the shared_cpu_list file when interpreting the output.
Observability checklist
- Record CPU model, memory type/configuration, storage model, operating system, and benchmark build flags.
- Use
perf stat -e cycles,instructions,cache-misses,cache-referencesas a first look on Linux; supported hardware events vary by CPU. - Compare application latency with device-level I/O metrics when storage is involved.
- Repeat measurements and report a median or distribution instead of relying on one run.
- Treat a counter as a clue. Confirm suspected cache or storage bottlenecks with a profile and a controlled workload change.
Common interpretation mistakes
- A cache hit latency is not the same as the time per array element in a streaming benchmark.
- A larger cache does not guarantee a faster application; layout, concurrency, and working-set shape matter.
- A cache line is not the same size on every architecture.
- Storage datasheet throughput does not predict small random I/O latency or end-to-end application response time.
- Memory capacity, bandwidth, and latency are separate properties. More capacity does not automatically increase bandwidth.
Quick Recap
- The hierarchy model helps explain data movement; it does not provide universal timing constants.
- Locality can reduce how often a program waits on slower memory levels.
- Latency and bandwidth describe different limits and need different benchmarks.
- Capacity and cache sharing depend on the processor model and configuration.
- Storage results must include device and workload details.
Further Reading
- Intel Core i7-12700 specifications
- Intel Core Ultra 7 265K specifications
- Intel 64 and IA-32 Architectures Optimization Reference Manual
- Linux perf documentation
- Cache & Buffer Management — CPU cache coherence and the operating-system page cache
- Paging & Page Tables — how the OS maps virtual pages to physical frames
Conclusion
The hierarchy helps explain where a program gets its data, but it cannot predict an exact runtime. A sequential scan and a dependent pointer chase can behave very differently on the same machine. Record the hardware and workload whenever you report a measurement.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.