Lesson 3 · Memory management

Memory Hierarchy

No single memory is fast, large and cheap at once. A computer stacks several kinds, small and fast near the CPU and large and slow further away, and relies on locality to make the stack feel fast.

Memory Hierarchy concept diagramA pyramid of six levels from registers at the top to tape at the bottom, each wider than the one above, with typical access times from under a nanosecond to seconds and sizes from bytes to petabytes.registers< 1 ns · bytescache L1–L31–10 ns · KB–MBmain memory~100 ns · GBSSD~100 µs · TBhard disk~10 ms · TBtape / archiveseconds · PBfasterlargercheaperregisters, cache and main memory are volatile; SSD, disk and tape keep data without power
1

Why Memory Comes in Levels

The memory hierarchy of a computer is the arrangement of storage in levels, ordered by speed, size and cost: registers, cache, main memory, SSD, hard disk and tape. Each level down is larger, slower and cheaper per byte than the one above, as the pyramid at the top of the page shows.

The trade-off is physical, not a design accident. Fast memory (SRAM) needs six transistors per bit and must sit close to the CPU; dense memory (DRAM, flash, magnetic media) is cheaper per bit but slower to reach. No technology is fast, huge and cheap at once, so computers combine them.

The goal of the hierarchy is a memory that appears as large as the bottom level and almost as fast as the top. Whether it succeeds depends on locality, covered next.

  • Speed gaps are large: ns → µs → ms
  • Registers, cache and RAM lose data without power; SSD, disk and tape keep it
2

Locality of Reference: Why the Hierarchy Works

Programs do not touch memory at random. At any moment they use a small part of their data and code heavily, and that is locality of reference.

Temporal locality: data used now is likely to be used again soon, such as a loop counter or a function called repeatedly. Spatial locality: data near what is used now is likely to be used soon, such as the next element of an array or the next instruction.

Each level exploits both. It keeps recently used data (temporal) and fetches data in blocks rather than bytes, a 64-byte cache line or a 4 KB page (spatial). Because of locality, a cache holding a tiny fraction of memory can serve 95% or more of all accesses. The tracer below shows it: a cache of three lines answers six of ten references because A and B keep coming back.

The two kinds of locality
Temporal localitySpatial locality
MeaningThe same address is reused soonNearby addresses are used soon
ExampleLoop counter, hot functionArray traversal, straight-line code
How levels exploit itKeep recently used blocksMove whole blocks, lines or pages
  • Temporal: reuse of the same data
  • Spatial: use of neighbouring data
  • Caches keep recent blocks and fetch whole lines
  • Without locality, the hierarchy would be as slow as its bottom level
3

Levels of the Memory Hierarchy

Each level is managed by a different part of the system. The hardware decides what lives in the caches; the operating system decides which pages of a process are in main memory and which are on disk, through virtual memory and page replacement. The TLB is itself a small cache, of address translations rather than data.

Data moves between adjacent levels in fixed units: cache lines between cache and RAM, pages between RAM and disk. A reference that misses at one level is passed down to the next.

Typical figures for a modern computer
LevelTechnologyTypical sizeAccess timeManaged by
RegistersFlip-flops in the CPU< 1 KB< 1 nsCompiler
L1 / L2 / L3 cacheSRAM64 KB – 64 MB1 – 10 nsHardware
Main memoryDRAM8 – 512 GB~100 nsOperating system
SSDNAND flash0.5 – 8 TB~100 µsOS + device controller
Hard diskMagnetic platters1 – 20 TB~10 msOS + device controller
Tape / archiveMagnetic tapePBsecondsBackup software
  • Transfer units grow downwards: words, lines, pages, blocks
  • Each level acts as a cache for the level below
Key reference

Terms, operations, and practical uses

Key terms

  • Hit / missWhether the requested data is present at a level.
  • Hit ratioFraction of accesses a level answers; miss ratio is 1 minus it.
  • Effective access timeThe probability-weighted average cost of one access.
  • Cache lineThe block moved between cache and memory, typically 64 bytes.

Miss types

  • CompulsoryFirst use of a block; unavoidable without prefetching.
  • CapacityThe working set is larger than the level.
  • ConflictBlocks compete for the same slot in a set-associative or direct-mapped cache.
Implementation

LRU cache over a reference string

from collections import OrderedDict

CACHE_LINES = 3
CACHE_NS, MEMORY_NS = 1, 100
REFERENCES = ["A", "B", "A", "C", "A", "B", "D", "A", "B", "A"]


def simulate(references, lines):
    cache = OrderedDict()  # least recently used first
    hits = 0
    for block in references:
        if block in cache:
            hits += 1
            cache.move_to_end(block)  # now the most recently used
            outcome = "hit"
        else:
            if len(cache) == lines:
                evicted, _ = cache.popitem(last=False)
                outcome = f"miss, evict {evicted}"
            else:
                outcome = "miss"
            cache[block] = True
        print(f"{block}: {outcome:<14} cache = [{", ".join(cache)}]")
    return hits


hits = simulate(REFERENCES, CACHE_LINES)
n = len(REFERENCES)
miss_rate = (n - hits) / n
# Every access pays the cache lookup; a miss also pays main memory.
amat = CACHE_NS + miss_rate * MEMORY_NS
print(f"hits {hits}, misses {n - hits}, hit ratio {hits / n:.0%}")
print(f"average access time = {CACHE_NS} + {miss_rate:.1f} x {MEMORY_NS} = {amat:.0f} ns")
#include <algorithm>
#include <cstdio>
#include <list>
#include <string>
#include <vector>
using namespace std;

const size_t CACHE_LINES = 3;
const int CACHE_NS = 1, MEMORY_NS = 100;

int simulate(const vector<char>& references, size_t lines) {
    list<char> cache;  // least recently used first
    int hits = 0;
    for (char block : references) {
        string outcome;
        auto it = find(cache.begin(), cache.end(), block);
        if (it != cache.end()) {
            hits++;
            cache.erase(it);  // move to the most recently used end
            outcome = "hit";
        } else if (cache.size() == lines) {
            outcome = string("miss, evict ") + cache.front();
            cache.pop_front();
        } else {
            outcome = "miss";
        }
        cache.push_back(block);

        string shown;
        for (char c : cache) shown += (shown.empty() ? "" : ", ") + string(1, c);
        printf("%c: %-14s cache = [%s]\n", block, outcome.c_str(), shown.c_str());
    }
    return hits;
}

int main() {
    vector<char> references = {'A', 'B', 'A', 'C', 'A', 'B', 'D', 'A', 'B', 'A'};
    int n = references.size();
    int hits = simulate(references, CACHE_LINES);
    double missRate = double(n - hits) / n;
    // Every access pays the cache lookup; a miss also pays main memory.
    double amat = CACHE_NS + missRate * MEMORY_NS;
    printf("hits %d, misses %d, hit ratio %.0f%%\n", hits, n - hits, 100.0 * hits / n);
    printf("average access time = %d + %.1f x %d = %.0f ns\n", CACHE_NS, missRate, MEMORY_NS, amat);
}
import java.util.Iterator;
import java.util.LinkedHashSet;

public class Main {
    static final int CACHE_LINES = 3;
    static final int CACHE_NS = 1, MEMORY_NS = 100;

    static int simulate(char[] references, int lines) {
        LinkedHashSet<Character> cache = new LinkedHashSet<>(); // least recently used first
        int hits = 0;
        for (char block : references) {
            String outcome;
            if (cache.remove(block)) {
                hits++;
                outcome = "hit"; // re-added below as the most recently used
            } else if (cache.size() == lines) {
                Iterator<Character> oldest = cache.iterator();
                outcome = "miss, evict " + oldest.next();
                oldest.remove();
            } else {
                outcome = "miss";
            }
            cache.add(block);
            System.out.printf("%c: %-14s cache = %s%n", block, outcome, cache);
        }
        return hits;
    }

    public static void main(String[] args) {
        char[] references = "ABACABDABA".toCharArray();
        int n = references.length;
        int hits = simulate(references, CACHE_LINES);
        double missRate = (double) (n - hits) / n;
        // Every access pays the cache lookup; a miss also pays main memory.
        double amat = CACHE_NS + missRate * MEMORY_NS;
        System.out.printf("hits %d, misses %d, hit ratio %.0f%%%n", hits, n - hits, 100.0 * hits / n);
        System.out.printf("average access time = %d + %.1f x %d = %.0f ns%n", CACHE_NS, missRate, MEMORY_NS, amat);
    }
}
Watch it run

Step through it

Running on references A B A C A B D A B A, then a loop A B C D; 3 cache lines; cache 1 ns, memory 100 ns

reference stringABACABDABACPUcache · 3 lines · 1 ns · LRU → MRUmain memory · 100 nsABCDcold cachehits0misses0hit ratio—avg access—every line starts empty
Step 1

A 3-line cache in front of main memory

The CPU asks for blocks in the order shown. A block found in the cache costs 1 ns; otherwise it is fetched from main memory at 100 ns and copied into the cache, evicting the least recently used line if the cache is full.

Output
1 / 12
4

Hit Ratio and Effective Access Time

  1. Hit – the requested data is found at this level.
  2. Hit ratio h – hits ÷ total accesses; miss ratio = 1 − h.
  3. Look-through (hierarchical) access – check level 1 first; on a miss, go to level 2. EAT = h·t₁ + (1 − h)·(t₁ + t₂).
  4. Look-aside (simultaneous) access – start both levels at once and use whichever answers. EAT = h·t₁ + (1 − h)·t₂.

The effective access time (EAT), also called average memory access time, is the expected time of one access, weighted by how often each level answers. For a cache, the weight is the cache hit ratio: the share of accesses the cache answers without going to RAM.

The look-through form can also be written EAT = t₁ + (1 − h)·t₂: every access pays the level-1 lookup, and misses also pay level 2. With t₁ = 1 ns, t₂ = 100 ns and h = 0.6, as in the tracer, EAT = 1 + 0.4 × 100 = 41 ns. Raise h to 0.95 and it falls to 6 ns.

Read the question for which model it assumes. If it says the levels are accessed simultaneously, a miss costs only t₂; if it says the second level is accessed after a miss, a miss costs t₁ + t₂.

  • Small changes in h move EAT a lot when t₂ ≫ t₁
  • Always state which access model you used
5

Worked Example: Effective Access Time for Three Levels

A cache hit costs t₁. A cache miss that hits memory costs t₁ + t₂. A miss in both costs t₁ + t₂ + t₃.

  • Cache – t₁ = 2 ns, hit ratio h₁ = 0.95.
  • Main memory – t₂ = 100 ns, hit ratio h₂ = 0.9999 for accesses that miss the cache.
  • Disk – t₃ = 10 ms = 10,000,000 ns, for accesses that miss both.
  • Model – look-through: each level is tried only after the one above misses.

Step 1, cost of a cache miss. 0.9999 × (2 + 100) + 0.0001 × (2 + 100 + 10,000,000) = 101.99 + 1,000.01 = 1,102.0 ns.

Step 2, overall EAT. 0.95 × 2 + 0.05 × 1,102.0 = 1.9 + 55.1 = 57.0 ns.

Step 3, read the result. Without the disk term the answer would be 0.95 × 2 + 0.05 × 102 = 7.0 ns. A page fault rate of one in ten thousand cache misses multiplies the average access time by eight. This is why operating systems work so hard to avoid page faults, and why thrashing is catastrophic.

  • Multiply each path's probability by its full time
  • The rarest path, the disk, adds the most time: 50 of the 57 ns
  • Tiny fault rates matter because disk is 10⁵ times slower than RAM
6

Design Issues Across the Hierarchy

Replacement. When a level is full, something must be evicted. Hardware caches use LRU or a cheap approximation; the OS chooses among pages with algorithms such as LRU and Clock.

Write policy. A write can go through to the level below at once (write-through: simple, always consistent, slower) or wait until the block is evicted (write-back: fast, but the lower level is briefly stale and a dirty bit is needed).

Consistency. With several cores, each with its own cache, the same address can have several copies. Cache coherence protocols such as MESI keep them in agreement. Between RAM and disk, the OS flushes dirty pages so that the persistent copy is eventually correct.

Inclusion. In an inclusive hierarchy every block in a higher level is also in the level below, which simplifies coherence at the cost of duplicated space.

  • Write-through vs write-back: consistency vs speed
  • Edge case: an access pattern that cycles through one block more than a level holds misses every time under LRU