本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
12Caches and the Memory Hierarchy
Here is a program that adds up the integers of a matrix twice: once row by row, once column by column. The two loops perform the same additions on the same numbers and print the same sum.
clock_gettime(CLOCK_MONOTONIC, &t0);
long rows = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
rows += a[(long)i * N + j]; /* consecutive addresses */
double t_rows = ms_since(t0);
clock_gettime(CLOCK_MONOTONIC, &t0);
long cols = 0;
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
cols += a[(long)i * N + j]; /* addresses 16 KiB apart */
double t_cols = ms_since(t0);
$ gcc -std=c17 -O2 -Wall -Wextra -o rows_cols rows_cols.c -lm && ./rows_cols
row order: sum 50331645 in 6.1 ms
column order: sum 50331645 in 205.7 ms, 33.5 times slower
-O2.The column order is about thirty times slower. Nothing in the instructions explains it: both loops execute one load and one addition per element. The difference lies in where the loaded integers come from. A load that finds its word in a small memory next to the processor takes about a nanosecond; a load that must go to the memory modules on the motherboard takes more than a hundred. This chapter explains what these small memories are, how they decide what to keep, how to count their misses with a simulator fed by rv, and how to write code that they serve well.
You already know
Book 1: the memory (RAM) holds the running programs and their data and is emptied when the power goes off; a disk keeps files. Book 3: a process’s memory is a sequence of bytes with addresses; a two-dimensional C array is stored row after row, so that a[i][j] of an array lies at offset times the size of an element. Chapter 10: lw and sw compute an address and access one word. Chapter 11: the memory stage of the pipeline was assumed to take one cycle.
12.1 Locality and the memory hierarchy
The previous chapter assumed that a load takes one cycle. A memory that is both large and that fast cannot be built: a larger memory has longer wires and more cells to select from, and the memory chips sit centimetres away from the processor. What can be built is a small fast memory beside a large slow one. It pays because programs do not use their addresses at random.
Definition 12.1 (Temporal locality, spatial locality)
A program has temporal locality when an address it has just used is likely to be used again soon, and spatial locality when the addresses near an address it has just used are likely to be used soon.
A loop has both: its instructions are fetched again at every turn (temporal), and a walk along an array uses consecutive addresses (spatial). The row-order sum of the hook has spatial locality; the column order jumps bytes at every step and has none, as long as a column does not fit in the fast memory.
Definition 12.2 (Memory hierarchy)
A memory hierarchy is a sequence of memories, each larger and slower than the one before it, where each level keeps copies of the parts of the next level that were used recently. From the processor outwards: the registers, two or three levels of cache, the main memory, and the disks.
The levels can be measured from a program. The trick is to make every load depend on the one before, so that the processor cannot overlap them: a buffer is filled with pointers that form a single random cycle through its 64-byte blocks, and the program follows the pointers. The time per step is then the time of one load, and it depends on which level holds the buffer.
for (long size = 4096; size <= 256L << 20; size *= 2) {
long n = size / LINE;
char *buf = aligned_alloc(LINE, size);
long *order = malloc(sizeof(long) * n);
for (long k = 0; k < n; k++)
order[k] = k;
for (long k = n - 1; k > 0; k--) { /* Sattolo: a single random cycle */
long r = (long)(next_random() % (uint64_t)k);
long t = order[k]; order[k] = order[r]; order[r] = t;
}
for (long k = 0; k < n; k++) /* line order[k] points to line order[k+1] */
*(char **)(buf + order[k] * LINE) = buf + order[(k + 1) % n] * LINE;
char *p = buf;
for (long k = 0; k < n; k++) /* one pass to warm the caches */
p = *(char **)p;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (long k = 0; k < STEPS; k++)
p = *(char **)p; /* each load needs the one before */
clock_gettime(CLOCK_MONOTONIC, &t1);
double ns = ((t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec)) / STEPS;
printf("%10ld %10.2f%s\n", size >> 10, ns, p == NULL ? "!" : "");
free(order);
free(buf);
}
$ gcc -std=c17 -O2 -Wall -Wextra -o sweep sweep.c -lm && ./sweep
size KiB ns/access
4 1.09
8 1.17
16 1.09
32 1.17
64 3.84
128 3.98
256 3.86
512 4.61
1024 5.15
2048 8.97
4096 19.92
8192 43.30
16384 140.66
32768 150.22
65536 151.73
131072 162.24
262144 168.99
getconf reports them below. Each time the buffer outgrows a level, the time of a load rises to that of the next.The curve has four plateaus. Up to 32 KiB a load takes about one nanosecond; from 64 KiB to 1 MiB, about four; around 4 MiB, about twenty; beyond 16 MiB, about 150. A step need not fall exactly at a capacity: a cache is shared with other programs, and when random addresses cover thousands of memory pages the processor’s translation of addresses, a subject of operating systems, adds misses of its own. Registers do not appear in the sweep: they are read within the cycle of the instruction that names them. Disks are much slower again, and a program reaches them only through the operating system, as Chapter 14 shows.
getconf; the times are the plateaus of Output 12.2, the time of one load served by that level.
History — A slave memory
In April 1965 M. V. Wilkes published a two-page paper proposing a small fast “slave memory” that would hold copies of the words of a large slow main memory most recently used, so that most accesses would be as fast as the small memory. In 1968 a description of a large commercial computer, the IBM System/360 Model 85, called such a buffer a cache, and the word stayed.
12.2 Direct-mapped caches
Definition 12.3 (Cache, line, hit, miss)
A cache is a small fast memory that holds copies of blocks of a larger memory. The block it moves at once, bytes with a power of two at an address multiple of , is a cache line. An access whose line is in the cache is a hit; otherwise it is a miss, and the line is fetched from the next level. The hit rate of a run is its number of hits divided by its number of accesses, and the miss ratio is one minus the hit rate.
The hook’s laptop has 64-byte lines: the first load of a row brings 16 integers, and the next 15 loads hit. That is why the row-order sum is fast: it misses once every 16 integers. A cache must decide, for each line, where it may be stored and how to find it again. The simplest rule gives every line exactly one place.
Definition 12.4 (Tag, index and offset fields)
In a cache of sets of lines of bytes, with and powers of two, an address is cut into three fields: the offset field, its low bits, which select a byte in the line; the index field, the next bits, which select the set; and the tag field, the remaining high bits, stored beside the line to tell which of the many lines that share the set is there.
Definition 12.5 (Direct-mapped, set-associative, fully associative)
A cache is direct-mapped when each set holds one line, so that a line can be in one place only; -way set-associative when each set holds lines, any of which may receive a line of that set; and fully associative when there is one set, so that any line can go anywhere.
Proposition 12.6 (Field widths)
A cache of bytes, -way set-associative with lines of bytes, all powers of two, has sets. With -bit addresses, its offset field has bits, its index field bits, and its tag field bits.
Proof. The cache holds lines, grouped per set, hence sets. A byte in a line of bytes is named by bits, a set among by bits, and the tag keeps all the other bits, because two lines that share an index differ only there: knowing the set and the tag, the line’s address is the tag, then the index, then zero bits. ∎
The simulator cache.py implements the three kinds at once: ways = 1 gives a direct-mapped cache, ways equal to the number of lines a fully associative one. Each set is an ordered dictionary from tags to a “dirty” flag, kept in the order of last use; the flag and the order serve in the next section.
class Cache:
"""size and line in bytes; ways = 1 is direct-mapped, ways = size // line is fully
associative. write_back: dirty lines are written to memory when evicted;
otherwise every store goes to memory at once (write-through)."""
def __init__(self, size, line, ways, write_back=True, write_allocate=True):
self.line, self.ways = line, ways
self.sets = size // (line * ways)
self.offset_bits = line.bit_length() - 1
self.index_bits = self.sets.bit_length() - 1
self.write_back, self.write_allocate = write_back, write_allocate
self.data = [OrderedDict() for _ in range(self.sets)] # tag -> dirty, LRU first
self.hits = self.misses = self.memory_writes = 0
def split(self, addr):
"""(tag, index, offset) of an address."""
offset = addr & (self.line - 1)
index = (addr >> self.offset_bits) & (self.sets - 1)
tag = addr >> (self.offset_bits + self.index_bits)
return tag, index, offset
def access(self, addr, write=False):
"""One load or store; returns True on a hit."""
tag, index, _ = self.split(addr)
s = self.data[index]
if tag in s:
self.hits += 1
s.move_to_end(tag) # now the most recently used
if write:
s[tag] = s[tag] or self.write_back
self.memory_writes += not self.write_back
return True
self.misses += 1
if write and not self.write_allocate:
self.memory_writes += 1 # the store goes around the cache
return False
if len(s) == self.ways:
_, dirty = s.popitem(last=False) # evict the least recently used
self.memory_writes += dirty
s[tag] = write and self.write_back
self.memory_writes += write and not self.write_back
return False
Method 12.7 (Tracing a direct-mapped cache by hand)
Start from an empty cache. For each address: write it in binary and cut it into tag, index and offset; look at the set given by the index; if it holds the same tag, it is a hit; otherwise it is a miss, and the set now holds the new tag, whatever it held before. Keep a table with one row per set and update it at each miss.
A cache of 256 bytes with 16-byte lines has 16 sets: 4 offset bits, 4 index bits. Here is a trace of eight accesses:
$ python hand_trace.py
address tag index offset result
0x00000 0 0 0 miss
0x00004 0 0 4 hit
0x00010 0 1 0 miss
0x00100 1 0 0 miss
0x00000 0 0 0 miss
0x00110 1 1 0 miss
0x00014 0 1 4 miss
0x00200 2 0 0 miss
1 hit, 7 misses; valid sets: {0: [2], 1: [0]}
0x004 hits because 0x000 brought the whole line 0x000 to 0x00f. 0x100 has the same index as 0x000 and another tag: it evicts it, and the following 0x000 misses again, although the cache has fourteen empty sets. Two lines that keep evicting each other while space is free elsewhere are the weakness of the direct mapping.
The same simulator can be fed with real programs. matrix_sum.S fills a matrix of words and sums it in the order its input chooses; trace_demo.py runs it on rv and keeps the address of every load, through the trace callback met in Chapter 11. Like the short programs of Chapter 10, its main uses s registers without saving them, which only rv, where nothing runs after main, tolerates.
outer: li t1, 0 # inner counter
inner: mv t4, t0 # row order: i = outer, j = inner
mv t5, t1
beqz s2, addr
mv t4, t1 # column order: i = inner, j = outer
mv t5, t0
addr: mul t2, t4, s1
add t2, t2, t5
slli t2, t2, 2
add t2, s0, t2
lw t3, 0(t2) # the load the cache sees
add a0, a0, t3
addi t1, t1, 1
blt t1, s1, inner
addi t0, t0, 1
blt t0, s1, outer
s2 chooses which counter is the row code/bachelor-2/12-caches/listings/matrix_sum.Sdef load_addresses(order):
m = Machine(open("matrix_sum.S").read(), inputs=[order])
loads = []
m.run(trace=lambda s: loads.append(s.mem_addr) if s.mem_kind == "load" else None)
return m.output_text, loads
def main():
for order, name in [(0, "row order"), (1, "column order")]:
out, loads = load_addresses(order)
c = Cache(size=1024, line=32, ways=1)
for addr in loads:
c.access(addr)
print(f"{name:<13} sum {out} {len(loads)} loads {c.hits:>4} hits"
f" {c.misses:>4} misses miss ratio {c.miss_ratio():.3f}")
print(" first addresses:", " ".join(f"{a:#x}" for a in loads[:4]))
$ python trace_demo.py
row order sum 31744 1024 loads 896 hits 128 misses miss ratio 0.125
first addresses: 0x10000000 0x10000004 0x10000008 0x1000000c
column order sum 31744 1024 loads 0 hits 1024 misses miss ratio 1.000
first addresses: 0x10000000 0x10000080 0x10000100 0x10000180
In row order the addresses step by 4 and each 32-byte line serves 8 loads: 128 misses for 1024 loads, a miss ratio of . In column order they step by 128 bytes, a whole row; every load misses. Yet the matrix’s 32 rows need only 32 lines in a column, and the cache has 32 lines. Section 12.4 finds out why they do not stay.
12.3 Associative caches and write policies
An -way cache lets lines of the same index live together. On a miss in a full set, one of them must go.
Definition 12.8 (Replacement policy, LRU)
The replacement policy of a set-associative cache chooses which line of a full set a miss evicts. The least recently used (LRU) policy evicts the line whose last access is the oldest.
In hardware, a 2-way set needs one bit to remember which of its two lines is older; the simulator keeps each set’s tags in order of use and moves a tag to the end on every hit (move_to_end), so that the first tag is always the one to evict (popitem(last=False)).
Stores raise a second question: when the cache holds a copy of a line, a store changes the copy, and the memory below must eventually see the change.
Definition 12.9 (Write-through, write-back, write-allocate)
A write-through cache sends every store to the next level as well. A write-back cache only changes its copy and marks the line dirty; a dirty line is written to the next level when it is evicted. A cache is write-allocate when a store that misses first brings the line into the cache; otherwise the store goes to the next level and the cache is unchanged.
Write-back saves traffic when a line is written many times before it leaves: a loop that adds into the same counter a million times writes memory once. Write-through keeps the next level always up to date, at the cost of one memory write per store. In cache.py, the value stored in a set’s dictionary is the dirty flag: an eviction adds it to memory_writes, and a write-through cache adds one at every store.
12.4 Three kinds of misses
Definition 12.10 (Compulsory, capacity and conflict misses)
A miss is compulsory when its line was never accessed before: every cache misses it. It is a capacity miss when a fully associative LRU cache of the same size would also miss it: the program used more distinct lines since the last use of this one than the cache can hold. Otherwise it is a conflict miss: only the mapping of lines to sets caused it.
The definition is a recipe: run the trace on the cache and, beside it, on a fully associative “shadow” cache of the same size, and classify each miss by what the shadow did. Exercise 12.7 writes the classifier; here is its verdict on the column-order sum, and on a loop that sweeps 33 lines over and over through a cache of 32.
$ python three_c_demo.py
column order
direct-mapped 1024 misses = 128 compulsory + 0 capacity + 896 conflict
2-way 1024 misses = 128 compulsory + 0 capacity + 896 conflict
fully associative 128 misses = 128 compulsory + 0 capacity + 0 conflict
cyclic sweep of 33 lines
direct-mapped 51 misses = 33 compulsory + 18 capacity + 0 conflict
2-way 60 misses = 33 compulsory + 27 capacity + 0 conflict
fully associative 330 misses = 33 compulsory + 297 capacity + 0 conflict
In column order, 896 of the 1024 misses are conflicts. A column visits addresses 128 bytes apart; with 32-byte lines and 32 sets, the index is bits 5 to 9 of the address, and adding 128 adds 4 to it: the 32 lines of a column fall into the 8 sets whose index is a multiple of 4 (the column’s first line decides which multiple), and the other 24 sets stay empty. Two ways do not help: with 16 sets of two ways, the 32 lines then fall in 4 sets, 8 places for 32 lines. A fully associative cache of the same size keeps the 32 lines and misses only on first use. The cyclic sweep shows the opposite case.
Proposition 12.11 (A cyclic sweep defeats LRU)
A fully associative LRU cache of lines, accessed cyclically over distinct lines , misses on every access.
The proof is Exercise 12.8; the simulator checks it for several in the chapter’s tests, and the output above shows it for : 330 accesses, 330 misses. The direct-mapped cache does better on this sweep, 51 misses, because it evicts only the line that shares a set with the newcomer: lines and fight over set 0, and the 31 others stay. LRU, a good policy for most programs, is the worst possible one for a loop just too large for the cache. The cure is to make the loop’s data fit: the 18 misses left even in the direct-mapped cache are still capacity misses.
Proposition 12.12 (Row and column order)
Let an matrix of -byte elements be stored row after row, with each row a whole number of lines of bytes, and read once, from a cold fully associative LRU cache of lines. In row order the reads miss times. In column order they miss times if , and times, on every read, if .
Proof. A line holds consecutive elements of one row. In row order each line is read in consecutive accesses: the first misses (compulsory) and the others hit, since nothing comes between them. That gives one miss per line, and the matrix has lines. In column order, the element and the next element of its line, , are read accesses apart. Between them come the elements and : elements of other rows, hence of distinct lines, each read once. Under LRU the line of is still present after them if and only if the cache holds at least lines. If , every line misses only on its first access; if , every access finds its line evicted. ∎
The hook’s matrix has rows; a column needs 4096 lines of 64 bytes, 256 KiB, more than the 48 KiB L1. By the proposition every load of the column order misses in L1, against one in 16 for the row order. In the simulator’s direct-mapped cache of Output 12.4, , but conflicts gave the column order the worst case anyway.
12.5 Code that respects the cache
Definition 12.13 (Loop interchange, blocking)
Loop interchange swaps two nested loops so that the inner loop walks consecutive addresses. Blocking, or tiling, cuts an array into tiles small enough to stay in the cache together, and does all the work on a tile, or on a few tiles, before moving on.
The product of two matrices, , is the classic case. Written as in the formula, its inner loop walks down a column: doubles, bytes apart. Interchanging the two inner loops makes every inner walk a row walk, for the same additions in another order.
static void ijk(int n, const double *A, const double *B, double *C)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
double s = 0;
for (int k = 0; k < n; k++)
s += A[i * n + k] * B[k * n + j]; /* B walked down a column */
C[i * n + j] = s;
}
}
static void ikj(int n, const double *A, const double *B, double *C)
{
for (int i = 0; i < n; i++) /* loop interchange: rows only */
for (int k = 0; k < n; k++) {
double a = A[i * n + k];
for (int j = 0; j < n; j++)
C[i * n + j] += a * B[k * n + j];
}
}
static void blocked(int n, const double *A, const double *B, double *C)
{
for (int ii = 0; ii < n; ii += T) /* ikj on T x T tiles that stay in cache */
for (int kk = 0; kk < n; kk += T)
for (int jj = 0; jj < n; jj += T)
for (int i = ii; i < ii + T; i++)
for (int k = kk; k < kk + T; k++) {
double a = A[i * n + k];
for (int j = jj; j < jj + T; j++)
C[i * n + j] += a * B[k * n + j];
}
}
$ gcc -std=c17 -O2 -Wall -Wextra -o matmul matmul.c -lm && ./matmul
n = 1024 ijk 2944.4 ms check 36
n = 1024 ikj 302.1 ms check 36
n = 1024 blocked 472.0 ms check 36
n = 2048 ikj 5664.1 ms check -59
n = 2048 blocked 3911.3 ms check -59
The interchange alone makes the product about ten times faster. Blocking is slower than the plain interchanged loop at this size: the three matrices take 8 MiB each, fits in the 24 MiB L3, and the processor fetches the next lines of a row walk ahead of the loads that need them (prefetching), so that the row walks of ikj rarely wait. At each matrix takes 32 MiB, more than the L3. Then ikj reads the whole of from memory for every row of : its time grows about nineteen-fold for eight times the arithmetic. The tiled version reuses each tile of for 64 rows of while it is in cache, and its time grows about eightfold, like the arithmetic. Blocking pays when the data no longer fits.
Records raise the same question at another scale. A catalogue of books stored as an array of structures puts each book’s fields together; a structure of arrays stores each field in its own array. A loop that reads one field of every record uses all of each line in the second layout and an eighth of it in the first.
struct book { double price; double weight; long isbn; int pages; int year; char shelf[32]; };
struct books { double *price; double *weight; long *isbn; int *pages; int *year; };
double t0 = now_ms(), s1 = 0;
for (long k = 0; k < M; k++)
s1 += aos[k].price; /* 8 useful bytes out of each 64-byte line */
double t_aos = now_ms() - t0;
t0 = now_ms();
double s2 = 0;
for (long k = 0; k < M; k++)
s2 += soa.price[k]; /* every byte of every line is used */
double t_soa = now_ms() - t0;
$ gcc -std=c17 -O2 -Wall -Wextra -o aos_soa aos_soa.c -lm && ./aos_soa
struct size 64 bytes
array of structures: mean 25.00 in 12.39 ms
structure of arrays: mean 25.00 in 2.85 ms, 4.3 times faster
Each structure takes 64 bytes, a line’s worth, of which the loop reads 8: it moves eight times as many bytes from memory as the arrays layout, and the measured ratio is about four. The arrays loop is held back by its own chain of additions, each waiting for the one before (the compiler may not reorder a floating-point sum), rather than by memory: 2.85 ms for additions is about 0.7 ns each, while the structures loop moves 256 MiB in 12.39 ms, about 22 GB/s, a bandwidth figure. The array of structures is the right layout when every use of a record reads most of its fields, as when a book is displayed; the structure of arrays when loops read one field of many records.
A program that tunes itself to the cache needs its parameters, and on Linux the C library reports them.
Facts as of 2026
The caches of the author’s laptop, as the C library reports them (sizes in bytes):
$ getconf -a | grep -E 'LEVEL[123]_D?CACHE_(SIZE|ASSOC|LINESIZE)'
LEVEL1_DCACHE_SIZE 49152
LEVEL1_DCACHE_ASSOC 12
LEVEL1_DCACHE_LINESIZE 64
LEVEL2_CACHE_SIZE 2097152
LEVEL2_CACHE_ASSOC 16
LEVEL2_CACHE_LINESIZE 64
LEVEL3_CACHE_SIZE 25165824
LEVEL3_CACHE_ASSOC 12
LEVEL3_CACHE_LINESIZE 64
getconf.By Proposition 12.6, its L1 data cache has sets, so 6 offset bits and 6 index bits; the L2 has 2048 sets and the L3 32 768. Another processor has other numbers; the command shows them.
In practice — Measuring before tuning
A loop that is slow because of the caches looks, in the source, exactly like a loop that is not. Measure first, with the real data size: the matrix product above needed blocking at one size and not at the other. Then try the cheap changes in order: walk arrays in the order they are stored, keep the data a loop reads small and together, and only then cut the work into tiles, whose best size depends on the machine.
12.6 Average memory access time
Definition 12.14 (Miss penalty, average memory access time)
The hit time of a level is the time of an access it serves; its miss penalty is the extra time of an access it misses, the time to get the line from the levels below. The average memory access time (AMAT) of a run is its total time spent on memory accesses divided by their number.
Proposition 12.15 (AMAT over several levels)
Let a hierarchy have cache levels above the main memory. Let be the extra time to reach level when level missed ( is the hit time of L1), the local miss ratio of level , the fraction of the accesses reaching level that miss there, and the extra time of the main memory. Then
Proof. By induction on . Let be the average extra time of an access that reaches level , counted from that level, with . Every access that reaches level pays , and the fraction of them that miss pays on top; averaging, . Every access reaches level 1, so , and unfolding the recurrence from to gives the formula. ∎
With the plateaus of Output 12.2 rounded to 1, 4, 20 and 150 ns, the extra times are , , and ns. For local miss ratios of 5 %, 20 % and 30 %:
Without any cache every access would take 150 ns, about ninety times longer. The formula also tells where to work: halving saves ns here, about as much as removing the trip to main memory altogether ( saves ns), and more than twice what removing the L3’s own extra time would ( ns).
12.7 Exercises
Exercise 12.1 ★
A direct-mapped cache of 128 bytes has 16-byte lines. Give its number of sets and the fields of an address, then trace the accesses 0x00, 0x04, 0x08, 0x10, 0x80, 0x00, 0x14, 0x90, 0x1C, 0x84 by Method 12.7. Which misses are compulsory?
Solution
Solution of Exercise 12.1.
sets: 4 offset bits (bits 3 to 0), 3 index bits (bits 6 to 4), and the tag is the address shifted right by 7. The trace: 0x00 set 0, tag 0, miss; 0x04 and 0x08 hit in the same line; 0x10 set 1, tag 0, miss; 0x80 set 0, tag 1, miss, evicting tag 0; 0x00 miss, evicting tag 1; 0x14 set 1, tag 0, hit; 0x90 set 1, tag 1, miss; 0x1C set 1, tag 0, miss; 0x84 set 0, tag 1, miss. Three hits and seven misses, MHHMMMHMMM, as the chapter’s tests check. The compulsory misses are the first accesses to the four lines 0x00, 0x10, 0x80 and 0x90; the three others are conflicts, since only four distinct lines are used and the cache has eight.
Exercise 12.2 ★
This simulator takes the index from the top bits of the address instead of the bits just above the offset. Explain its output on an array of 512 bytes read twice through a 1 KiB cache with 32-byte lines.
class WrongCache(Cache):
def split(self, addr):
offset = addr & (self.line - 1)
index = addr >> (32 - self.index_bits) # the top bits of the address
middle = 32 - self.index_bits - self.offset_bits # the bits in between
tag = (addr >> self.offset_bits) & ((1 << middle) - 1)
return tag, index, offset
array = [0x10000000 + 4 * k for k in range(128)] # 512 bytes, read twice
for cls in (Cache, WrongCache):
c = cls(size=1024, line=32, ways=1)
for addr in array + array:
c.access(addr)
print(f"{cls.__name__:<10} {c.hits:>4} hits {c.misses:>4} misses")
$ python exo_wrong_bits.py
Cache 240 hits 16 misses
WrongCache 224 hits 32 misses
Solution
Solution of Exercise 12.2.
The 512-byte array is 16 lines. With the correct mapping they go to 16 different sets of the 32: the first reading misses once per line (16 misses, 112 hits) and the second hits everywhere. With the wrong mapping the index is the top 5 bits of the address, the same, 2, for every address of the array: all 16 lines compete for one set of one line. Each line still serves its 8 words in a row, so each reading misses 16 times: 32 misses. Taking the index from the low bits above the offset spreads consecutive lines over all the sets, which is exactly what spatial locality needs; the high bits change only between distant regions of memory.
Exercise 12.3 ★
Write dirty_lines(cache), the number of lines a write-back Cache would still have to write to memory if it were emptied now, and total_writes(cache). How many memory writes do ten stores to the same word cause in a write-back cache, and in a write-through cache?
Solution
Solution of Exercise 12.3.
def dirty_lines(cache):
"""The lines that must be written to memory if the cache is emptied now."""
return sum(dirty for s in cache.data for dirty in s.values())
def total_writes(cache):
"""Writes to memory so far, plus those that emptying the cache would add."""
return cache.memory_writes + dirty_lines(cache)
Ten stores to one word in a write-back, write-allocate cache: the first misses and brings the line, marked dirty; the nine others hit. Nothing is written to memory until the line is evicted or the cache emptied: one write in all, which total_writes counts. A write-through cache writes memory ten times. The tests check both counts.
Exercise 12.4 ★
Give the fields of a 32-bit address for a 32 KiB 8-way cache with 64-byte lines, and for the laptop’s L2 of Output 12.8. How many bits of tag does each line of that L2 store?
Solution
Solution of Exercise 12.4.
sets: 6 offset bits, 6 index bits, tag bits. The L2 of Output 12.8 has sets: 6 offset bits, 11 index bits, and with 32-bit addresses tag bits per line (more on the laptop itself, whose addresses are wider).
Exercise 12.5 ★★
A 256-byte 2-way LRU cache has 16-byte lines. Trace 0x000, 0x100, 0x000, 0x200, 0x100, 0x084, 0x000, 0x300, 0x004, giving the contents of set 0 after each access. Then trace the same addresses through a direct-mapped cache of 256 bytes. Which does better, and why?
Solution
Solution of Exercise 12.5.
8 sets, 4 offset bits, index bits 6 to 4, tag the address shifted right by 7. Every address of the trace has index 0, 0x084 included (), with tags 0, 2, 0, 4, 2, 1, 0, 6, 0. Set 0, least recently used first: , , (hit), , , , , , (hit): two hits. In the direct-mapped cache of 256 bytes (16 sets, index bits 7 to 4), 0x000, 0x100, 0x200 and 0x300 all have index 0 and 0x084 index 8: every access evicts the one before in set 0, and all nine miss. The 2-way cache does better because the trace alternates between two lines of the same set, which it can hold together.
Exercise 12.6 ★★
This function sums each column of a grid of loan counts, one row per day and one column per book. Interchange its loops and measure.
static void col_sums_slow(const int *g, long *col)
{
for (int j = 0; j < COLS; j++) {
col[j] = 0;
for (int i = 0; i < ROWS; i++)
col[j] += g[(long)i * COLS + j];
}
}
Solution
Solution of Exercise 12.6.
static void col_sums_fast(const int *g, long *col) /* the loops interchanged */
{
for (int j = 0; j < COLS; j++)
col[j] = 0;
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
col[j] += g[(long)i * COLS + j];
}
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_colsums exo_colsums.c -lm && ./exo_colsums
column by column: 455.9 ms
row by row: 15.0 ms, 30.3 times faster, same sums: yes
The slow version walks a column, 16 KiB from one element to the next: by Proposition 12.12, with 8192 rows, every load misses in L1. The fast one walks the grid in the order it is stored, and the 4096 running sums, 32 KiB, stay in the L1 between rows. The same sums come out about thirty times faster.
Exercise 12.7 ★★
Write classify(addresses, size, line, ways), which returns the number of misses of a trace and their split into compulsory, capacity and conflict misses, by running a fully associative shadow cache beside the cache. Check that the three counts add up to the misses.
Solution
Solution of Exercise 12.7.
def classify(addresses, size, line, ways):
"""Runs the trace on the cache and on a fully associative LRU cache as large."""
cache = Cache(size, line, ways)
shadow = Cache(size, line, size // line) # same capacity, no conflict possible
seen = set()
counts = {"compulsory": 0, "capacity": 0, "conflict": 0}
for addr in addresses:
hit = cache.access(addr)
shadow_hit = shadow.access(addr)
block = addr // line
if not hit:
if block not in seen:
counts["compulsory"] += 1 # first use of the line: any cache misses
elif not shadow_hit:
counts["capacity"] += 1 # even full associativity misses
else:
counts["conflict"] += 1 # only the mapping made it miss
seen.add(block)
return cache.misses, counts
A line seen for the first time is compulsory, whatever the shadow did. Otherwise, if the shadow, fully associative with the same number of lines, also missed, the miss is one of capacity; if it hit, the mapping alone caused the miss. Each miss goes to exactly one branch, so the counts add up to the misses; the tests check it on random traces for four associativities, and Output 12.5 uses it.
Exercise 12.8 ★★
Prove Proposition 12.11. Does it still hold for a sweep over lines? Over lines?
Solution
Solution of Exercise 12.8.
First, a fully associative LRU cache of lines always holds the (at most ) distinct lines most recently used. By induction on the accesses: a hit only reorders them; a miss inserts the new line, which becomes the most recent, and if the cache was full, evicts the least recently used of the it held, which is the one that is no longer among the most recent. Now let access be to . For , the line is used for the first time: a miss. For , the accesses are to distinct lines, all different from , since any consecutive accesses of the sweep are to distinct lines. The cache holds exactly those lines, so access misses. Over lines, or any number more than , the same argument applies: the last accesses are to distinct lines other than the requested one. Over lines, the first accesses miss and all others hit, since the whole sweep fits.
Exercise 12.9 ★★
A transpose writes . Explain why its plain version is slow whichever loop is inside, write a tiled version and measure it for several tile sizes.
static void plain(const int *a, int *b) /* reads by rows, writes by columns */
{
for (long i = 0; i < N; i++)
for (long j = 0; j < N; j++)
b[j * N + i] = a[i * N + j];
}
int code/bachelor-2/12-caches/listings/transpose.cSolution
Solution of Exercise 12.9.
static void tiled(const int *a, int *b, int t) /* t x t tiles: both sides stay in cache */
{
for (long ii = 0; ii < N; ii += t)
for (long jj = 0; jj < N; jj += t)
for (long i = ii; i < ii + t; i++)
for (long j = jj; j < jj + t; j++)
b[j * N + i] = a[i * N + j];
}
$ gcc -std=c17 -O2 -Wall -Wextra -o transpose transpose.c -lm && ./transpose
plain 893.2 ms b[1][0] = 1
tiles of 8 127.5 ms b[1][0] = 1
tiles of 16 207.4 ms b[1][0] = 1
tiles of 32 211.9 ms b[1][0] = 1
tiles of 64 210.3 ms b[1][0] = 1
int.The plain version reads by rows but writes by columns, 32 KiB apart: every write is to a new line, and with 8192 rows, each line of is evicted before the next element of it is written, by Proposition 12.12. Exchanging the loops only moves the problem to the reads. A tile of uses lines of and lines of , each reused times while it stays in cache; tiles of 8 make the transpose about seven times faster here. A likely reason why larger tiles do worse: rows 32 KiB apart are a multiple of the L1’s 4 KiB of sets ( bytes), so all the lines of a tile’s column of fall in the same set of the L1, and 12 ways hold the 8 lines of a tile of 8 but not the 16 of a tile of 16. Those tiles still gain from the L2.
Exercise 12.10 ★★★
In the direct-mapped cache of Output 12.4, , yet the column order misses every time. Generalise: for an matrix of 4-byte words, a power of two at least 8, read in column order through a direct-mapped cache of lines of bytes, with and powers of two, , how many sets does a column use, and when does the column order miss on every read? Compare with Proposition 12.12.
Solution
Solution of Exercise 12.10.
A column steps by bytes, that is by lines, and the line of row has index for a constant . If , every row of the column falls in the same set; otherwise the column visits sets in turn (all powers of two). So a column uses sets. The line of is next needed at , which lies in the same line when . Between the two accesses, the column order reads rows of column and rows of column . If , rows or (one of them exists, since ) share the set of row , and their line, read in between, evicts it: every read misses. If , every row has its own set, and the column order misses only on the first uses. Now means : the cache must be as large as the whole matrix. For the chapter’s example, KiB and KiB, so every read misses. A fully associative cache needs only lines (Proposition 12.12), one column’s worth: the direct mapping costs a factor in size on this access pattern.
Exercise 12.11 ★★★
The simulator below counts the misses of a tiled transpose of a matrix of int, through a 4 KiB 4-way cache with 64-byte lines, for tile sizes 1 to 128. Explain each line of its output, in particular why the misses fall to tile size 8 and jump back at 16. What is the least possible number of misses?
def misses(t):
c = Cache(size=4096, line=64, ways=4)
for ii in range(0, N, t):
for jj in range(0, N, t):
for i in range(ii, ii + t):
for j in range(jj, jj + t):
c.access(A + 4 * (i * N + j))
c.access(B + 4 * (j * N + i), write=True)
return c.misses
$ python exo_block_size.py
tile misses per element
1 17408 1.062
2 9216 0.562
4 5408 0.330
8 4896 0.299
16 17408 1.062
32 17408 1.062
64 17408 1.062
128 17408 1.062
Solution
Solution of Exercise 12.11.
$ python exo_block_3c.py
tile 1: 17408 = 2048 compulsory + 15360 capacity + 0 conflict
tile 2: 9216 = 2048 compulsory + 7168 capacity + 0 conflict
tile 4: 5408 = 2048 compulsory + 3072 capacity + 288 conflict
tile 8: 4896 = 2048 compulsory + 1024 capacity + 1824 conflict
tile 16: 17408 = 2048 compulsory + 0 capacity + 15360 conflict
The cache has 64 lines in 16 sets; a row of either matrix is 512 bytes, 8 lines, so going down a column adds 8 to the index modulo 16: a column uses only 2 sets, 8 lines. Tile 1 is the plain transpose: is read by rows (1024 misses, one per line) and written by columns, each column touching 128 lines, more than the cache holds, so every write misses: . With tiles of , the writes into one line of come at a time, and the misses of fall to about : for . For and 8, the lines of a tile of and of the matching tile of fall in the same sets for some tiles, and the classifier finds 288, then 1824 conflict misses. At a tile’s column of has 16 lines in 2 sets of 4 ways: each line is evicted before its next write, and everything misses again, now as conflicts, since a fully associative cache would hold the tile. The least possible is the compulsory count, every line of both matrices once: , per element. Tile 8 is the best here, at 4896.
Exercise 12.12 ★★★
A machine has an L1 of hit time 1 ns and miss ratio 5 %, and a main memory 100 ns further away. An L2 is added, with an extra time of 4 ns. Below which local miss ratio does the L2 lower the AMAT? With a local miss ratio of 25 %, an L3 with an extra time of 15 ns is then added: below which local miss ratio does it pay? Compute the three AMATs for an L3 local miss ratio of 40 %.
Solution
Solution of Exercise 12.12.
Without L2, ns. With an L2 of local miss ratio , , lower than 6 if and only if , that is : the L2 pays for itself as soon as it catches more than 4 % of the L1’s misses. With , ns. Adding an L3 replaces the term by , lower if and only if . With : ns. The three AMATs are 6, 2.45 and about 1.89 ns: each level gains less than the one before, because it only acts on what the levels above it miss.
12.8 Problem: Why the image filter is slow
Problem 12.1
Weekend problem — Why the image filter is slow
A box blur replaces each pixel of a grey image by the mean of the pixels around it. The image is a square of pixels of 4 bytes, stored row after row; the blur reads the input image and writes a separate output image, and leaves the border unchanged. Lines are 64 bytes, so a line holds 16 pixels of a row.
static inline void blur_pixel(const int32_t *in, int32_t *out, int y, int x)
{
int32_t s = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
s += in[(y + dy) * N + x + dx];
out[y * N + x] = s / 9;
}
static void rows(const int32_t *in, int32_t *out)
{
for (int y = 1; y < N - 1; y++)
for (int x = 1; x < N - 1; x++)
blur_pixel(in, out, y, x);
}
static void columns(const int32_t *in, int32_t *out)
{
for (int x = 1; x < N - 1; x++)
for (int y = 1; y < N - 1; y++)
blur_pixel(in, out, y, x);
}
Part I — Counting by hand.
- How many reads of the input does the blur of an image perform? Give the number for .
- In row order, which input rows does the computation of output row read? Which of them were read for row ?
- Show that if the cache holds three rows of the image, every line of the input misses exactly once in row order.
- Deduce that the row order misses once every 16 pixels: a miss ratio of per pixel of the image, and per read.
- For and a 4 KiB cache, how many lines does a row take, and do three rows fit?
- In column order, how many distinct lines does one column of output read? Can the cache keep them until the next column needs them?
Part II — The simulator.
def read_misses(order, strip=16):
"""Misses of the reads of the input image; the output is written once per pixel."""
c = Cache(size=4096, line=64, ways=4)
for y, x in pixels(order, strip):
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
c.access(IN + 4 * ((y + dy) * N + x + dx))
return c.hits + c.misses, c.misses
$ python blur_sim.py
order reads misses per pixel
rows 580644 4096 0.0635
columns 580644 72704 1.1269
strips of 16 580644 11776 0.1825
strips of 64 580644 5632 0.0873
- Check the number of reads.
- Explain the 4096 misses of the row order exactly, and why the last column gives and not .
- In column order, show that each new output pixel brings one new line, except where and fall in different lines from . Deduce about misses per pixel, and compare with .
- Which kind of misses, in the sense of Definition 12.10, are those of the column order?
- Would a fully associative cache of 4 KiB do better in column order? Use Proposition 12.12.
- What is the least number of misses any order can have here?
Part III — Strips.
Some filters must go down the columns, for instance a vertical pass written for an image stored by columns. The remedy is to go down a strip of columns at a time, row by row inside the strip.
static void strips(const int32_t *in, int32_t *out, int w) /* columns, w at a time */
{
for (int x0 = 0; x0 < N; x0 += w)
for (int y = 1; y < N - 1; y++)
for (int x = x0 > 0 ? x0 : 1; x < x0 + w && x < N - 1; x++)
blur_pixel(in, out, y, x);
}
- For with strips aligned on lines, how many lines does one row of a strip read?
- Deduce the misses of the strips of 16 as a function of , and check the simulator’s 11 776.
- Do the same for , and explain why the simulator finds per pixel.
- Give the misses per pixel of strips of columns, a multiple of 16, when the cache holds three rows of a strip, and their limit as grows.
- How many lines must the cache hold for three rows of a strip of ? What is the widest strip that 64 lines allow? The cache has 16 sets of 4 ways, and a row of the image is 16 lines long, so the lines of a strip fall in the same sets on every row: what is then the widest strip it serves this way?
- Why is a strip of 16 worse than a strip of 64, although both use whole lines?
Part IV — Measured on the laptop.
$ gcc -std=c17 -O2 -Wall -Wextra -o blur blur.c -lm && ./blur
rows 53.7 ms check 517208
columns 483.7 ms check 517208
strips of 16 170.9 ms check 517208
strips of 64 69.3 ms check 517208
- For , how many KiB does a row take? Do three rows fit in the laptop’s L1 of 48 KiB? A column’s lines?
- By the simulator, how many times more misses does the column order have than the row order? How many times slower is it on the laptop?
- Explain the gap between the two ratios with the hierarchy of Section 12.1: which level serves the column order’s misses?
- Compare the measured times of the strips of 16 and of 64 with the row order. Is the order of the four times the order of the predicted miss ratios?
- Estimate, from the row order’s time, the time of one pixel and the time of one miss of the column order, assuming the row order’s time is all arithmetic.
- State the result of the problem.
Solution
Solution of Problem 12.1.
1. Nine reads per output pixel, and output pixels: , that is for .
2. Rows , and . Row read rows , and : two of the three were already read.
3. A line of input row is read for output rows , and , three consecutive rows. Between two consecutive uses, at output pixel of one row and output pixel of the next, the blur reads, at each column position, three lines: those of three rows to the right of in the first output row and to its left in the next. So fewer than three rows’ worth of distinct lines, plus a few at the ends, come in between. If the cache holds three rows, LRU keeps the line, and only its first use misses.
4. Every line misses once, so there are misses for pixels of the image: one every 16 pixels, a miss ratio of per pixel; since each pixel is read about nine times, per read.
5. A row is bytes, 16 lines; three rows are 48 lines, less than the 64 of a 4 KiB cache. The 16 lines of a row fall in the 16 sets, one each, so three rows put 3 lines in each 4-way set: they fit.
6. One column of output reads three columns of input over all rows: at least one line per row, 256 lines, and two per row where or is in another line. The cache has 64 lines: the lines of the first rows are gone when the next column needs them.
7. , the simulator’s figure.
8. The image is lines, and the row order misses once on each, by question 3. The last column divides by the output pixels, not by the pixels read: , against .
9. Output pixel comes after , which read rows to ; the lines of rows and are still in cache, and those of row are new. That is one line if , and are in the same line, that is , and two otherwise: on average misses per pixel. Exactly: each of the 224 columns of the first kind misses times (three rows at , then one per row), each of the 30 others 512 times: , the simulator’s count, and .
10. 4096 of them are compulsory, the first use of each line. The others are capacity misses: the line of is next needed one column later, after the lines of about 255 other rows, and a fully associative cache of 64 lines would not keep it either.
11. No: by Proposition 12.12, a column needs , here 256 lines, and the cache has 64.
12. 4096: every line must be read at least once, and the row order reaches that bound.
13. Three: the strip’s own line, and the lines holding and .
14. misses per strip, strips, less the missing left neighbour of the first strip and right neighbour of the last, lines each: .
15. Six lines per row of a strip of 64 (four of its own, two neighbours): , and .
16. misses per strip of pixels, so per pixel, which tends to , the row order’s ratio, as grows.
17. Three rows of the strip need lines; with 64 lines, , so . But rows 16 lines apart start in the same set: the consecutive lines of a row occupy as many consecutive sets, and three rows put three lines in each of them only if a row covers at most 16 sets. A row of more than 16 lines puts 6 lines in some 4-way sets. The widest strip is therefore , pixels.
18. Each strip also loads the lines of its two neighbours, which the neighbouring strips load again. A strip of 16 pays two extra lines for one useful one, per pixel; a strip of 64 two for four, .
19. KiB per row; three rows are 48 KiB, exactly the L1, which also holds the output and the stack, so the L1 is just short. A column’s lines, 4096 of 64 bytes and more where neighbours cross a line, are 256 to 512 KiB: far more than the L1, much less than the 2 MiB L2.
20. times more misses; measured, times slower.
21. The simulator has one cache of 4 KiB and counts every miss as a trip to memory. On the laptop the column order’s lines fit in the L2: its misses cost the L2’s few nanoseconds, not a trip to memory. Both orders also pay the same arithmetic, which dilutes the ratio, and the processor overlaps independent misses.
22. Measured: rows 53.7, strips of 64 69.3, strips of 16 170.9, columns 483.7 ms. Predicted per pixel: . The order is the same.
23. million pixels: about 3.2 ns per pixel in row order, 28.9 ns in column order, a difference of about 25.7 ns. The column order also writes its output down a column, so it misses about times per pixel on the reads and once on the writes: about 12 ns per miss, between the L2’s and the L3’s plateaus of Output 12.2. It is an estimate: overlap and prefetching blur it.
24. In row order the blur misses once every 16 pixels, a predicted miss ratio of , the least any order can reach; the column order misses more than once per pixel ( in the simulator, about eighteen times more), strips of columns sit between at ; and on the laptop the row order is measured nine times faster than the column order, with the four measured times in the order of the predicted miss ratios.
本章定义的术语
- Cache, line, hit, miss
- Compulsory, capacity and conflict misses
- Direct-mapped, set-associative, fully associative
- Loop interchange, blocking
- Memory hierarchy
- Miss penalty, average memory access time
- Replacement policy, LRU
- Tag, index and offset fields
- Temporal locality, spatial locality
- Write-through, write-back, write-allocate