计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

12Caches and the Memory Hierarchy

Here is a program that adds up the 4096×40964096 \times 4096 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);
Listing 12.1. The same sum, in two orders code/bachelor-2/12-caches/listings/rows_cols.c
$ 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
Output 12.1. One run on the author’s laptop, compiled with -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 n×mn \times m array lies at offset (im+j)(i m + j) 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 4096×4=16 3844096 \times 4 = 16\,384 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);
    }
Listing 12.2. Following a random cycle of pointers through buffers of growing size code/bachelor-2/12-caches/listings/sweep.c
$ 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
Output 12.2. One run on the author’s laptop: the time of a load, by the size of the buffer it is taken from.
The measurements of , on logarithmic scales. The dashed lines are the capacities of the laptop’s three caches, as getconf reports them below. Each time the buffer outgrows a level, the time of a load rises to that of the next.
The measurements of Output 12.2, on logarithmic scales. The dashed lines are the capacities of the laptop’s three caches, as 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.

The memory hierarchy of the author’s laptop. The capacities are those of getconf; the times are the plateaus of , the time of one load served by that level.
The memory hierarchy of the author’s laptop. The capacities are those of getconf; the times are the plateaus of Output 12.2, the time of one load served by that level.
The back of two laptop memory modules of 8 GB each. The gold contacts along the lower edge plug into the motherboard; an access that misses in every cache is served by modules like these. Photograph: ITEagle Europe – Sebastiaan Broekhoven, CC BY-SA 4.0.
The back of two laptop memory modules of 8 GB each. The gold contacts along the lower edge plug into the motherboard; an access that misses in every cache is served by modules like these. Photograph: ITEagle Europe – Sebastiaan Broekhoven, CC BY-SA 4.0.

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, BB bytes with BB a power of two at an address multiple of BB, 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 SS sets of lines of BB bytes, with SS and BB powers of two, an address is cut into three fields: the offset field, its low log⁡2B\log_2 B bits, which select a byte in the line; the index field, the next log⁡2S\log_2 S 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; AA-way set-associative when each set holds AA 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 CC bytes, AA-way set-associative with lines of BB bytes, all powers of two, has S=C/(AB)S = C / (A B) sets. With ww-bit addresses, its offset field has log⁡2B\log_2 B bits, its index field log⁡2S\log_2 S bits, and its tag field w−log⁡2S−log⁡2Bw - \log_2 S - \log_2 B bits.

Proof. The cache holds C/BC / B lines, grouped AA per set, hence S=C/(AB)S = C/(AB) sets. A byte in a line of B=2bB = 2^b bytes is named by bb bits, a set among S=2sS = 2^s by ss 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 bb zero bits. ∎

The fields of a 32-bit address for a direct-mapped cache of 512 bytes with 32-byte lines: 16 sets, so 4 index bits and 5 offset bits. The same address cut for another cache gives other fields.
The fields of a 32-bit address for a direct-mapped cache of 512 bytes with 32-byte lines: 16 sets, so 4 index bits and 5 offset bits. The same address cut for another cache gives other fields.

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
Listing 12.3. The cache’s shape code/bachelor-2/12-caches/listings/cache.py
    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
Listing 12.4. Splitting an address, and one access code/bachelor-2/12-caches/listings/cache.py

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]}
Output 12.3. A direct-mapped cache, access by access; the last line gives the tag held by each valid set.

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 cache after the trace of . Only two of its sixteen sets were ever used; the valid bit tells an empty set from a set holding tag 0.
The cache after the trace of Output 12.3. Only two of its sixteen sets were ever used; the valid bit tells an empty set from a set holding tag 0.

The same simulator can be fed with real programs. matrix_sum.S fills a 32×3232 \times 32 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
Listing 12.5. The sum: s2 chooses which counter is the row code/bachelor-2/12-caches/listings/matrix_sum.S
def 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]))
Listing 12.6. The loads of a run, through a 1 KiB direct-mapped cache with 32-byte lines code/bachelor-2/12-caches/listings/trace_demo.py
$ 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
Output 12.4. Row order and column order on the simulator.

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 1/81/8. 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 AA-way cache lets AA 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)).

Set 0 of a 256-byte 2-way cache with 16-byte lines (8 sets, so the tag is the address shifted right by 7), after each access of a trace. The LRU bit names the way to evict at the next miss. The third access hits; from then on each line is evicted just before it is needed again.
Set 0 of a 256-byte 2-way cache with 16-byte lines (8 sets, so the tag is the address shifted right by 7), after each access of a trace. The LRU bit names the way to evict at the next miss. The third access hits; from then on each line is evicted just before it is needed again.

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
Output 12.5. Misses classified, for three caches of 1 KiB with 32-byte lines.

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 CC lines, accessed cyclically over C+1C + 1 distinct lines ℓ0,ℓ1,…,ℓC,ℓ0,ℓ1,…\ell_0, \ell_1, \dots, \ell_C, \ell_0, \ell_1, \dots, misses on every access.

The proof is Exercise 12.8; the simulator checks it for several CC in the chapter’s tests, and the output above shows it for C=32C = 32: 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 ℓ0\ell_0 and ℓ32\ell_{32} 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 N×NN \times N matrix of ww-byte elements be stored row after row, with each row a whole number of lines of BB bytes, and read once, from a cold fully associative LRU cache of CC lines. In row order the reads miss N2w/BN^2 w / B times. In column order they miss N2w/BN^2 w / B times if C≥NC \ge N, and N2N^2 times, on every read, if C<NC < N.

Proof. A line holds B/wB/w consecutive elements of one row. In row order each line is read in B/wB/w 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 N2w/BN^2 w / B lines. In column order, the element (i,j)(i, j) and the next element of its line, (i,j+1)(i, j + 1), are read NN accesses apart. Between them come the elements (i+1,j),…,(N−1,j)(i + 1, j), \dots, (N - 1, j) and (0,j+1),…,(i−1,j+1)(0, j + 1), \dots, (i - 1, j + 1): N−1N - 1 elements of N−1N - 1 other rows, hence of N−1N - 1 distinct lines, each read once. Under LRU the line of (i,j)(i, j) is still present after them if and only if the cache holds at least NN lines. If C≥NC \ge N, every line misses only on its first access; if C<NC < N, every access finds its line evicted. ∎

The hook’s matrix has N=4096N = 4096 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, C=N=32C = N = 32, 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 n×nn \times n matrices, Cij=∑kAikBkjC_{ij} = \sum_k A_{ik} B_{kj}, is the classic case. Written as in the formula, its inner loop walks BB down a column: nn doubles, 8n8n 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];
        }
}
Listing 12.7. The product as written, and with its loops interchanged code/bachelor-2/12-caches/listings/matmul.c
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];
                    }
}
Listing 12.8. The interchanged product on 64×6464 \times 64 tiles code/bachelor-2/12-caches/listings/matmul.c
$ 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
Output 12.6. One run on the author’s laptop: three loop orders, two sizes. The check is a sum of entries of CC, the same for every order.

The interchange alone makes the 1024×10241024 \times 1024 product about ten times faster. Blocking is slower than the plain interchanged loop at this size: the three matrices take 8 MiB each, BB 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 n=2048n = 2048 each matrix takes 32 MiB, more than the L3. Then ikj reads the whole of BB from memory for every row of AA: its time grows about nineteen-fold for eight times the arithmetic. The tiled version reuses each tile of BB for 64 rows of AA while it is in cache, and its time grows about eightfold, like the arithmetic. Blocking pays when the data no longer fits.

Blocking the product. The tile of C at (ii, jj) accumulates the products of the tiles of A’s row ii by the tiles of B’s column jj; at each step kk only three tiles are in use, 3 × 64 × 64 doubles, 96 KiB, which stay in the L2 while they are reused 64 times.
Blocking the product. The tile of CC at (ii,jj)(ii, jj) accumulates the products of the tiles of AA’s row iiii by the tiles of BB’s column jjjj; at each step kkkk only three tiles are in use, 3×64×643 \times 64 \times 64 doubles, 96 KiB, which stay in the L2 while they are reused 64 times.

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; };
Listing 12.9. The same records, two layouts code/bachelor-2/12-caches/listings/aos_soa.c
    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;
Listing 12.10. The mean price, read from each layout code/bachelor-2/12-caches/listings/aos_soa.c
$ 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
Output 12.7. One run on the author’s laptop, for 2222^{22} books.

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 2222^{22} 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
Output 12.8. The cache parameters, by getconf.

By Proposition 12.6, its L1 data cache has 49 152/(12×64)=6449\,152 / (12 \times 64) = 64 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 1,…,k1, \dots, k above the main memory. Let hih_i be the extra time to reach level ii when level i−1i - 1 missed (h1h_1 is the hit time of L1), mim_i the local miss ratio of level ii, the fraction of the accesses reaching level ii that miss there, and TT the extra time of the main memory. Then

AMAT=h1+m1(h2+m2(h3+⋯+mk−1(hk+mkT)⋯ )).\mathrm{AMAT} = h_1 + m_1\bigl(h_2 + m_2\bigl(h_3 + \cdots + m_{k-1}(h_k + m_k T)\cdots\bigr)\bigr).

Proof. By induction on kk. Let PiP_i be the average extra time of an access that reaches level ii, counted from that level, with Pk+1=TP_{k+1} = T. Every access that reaches level ii pays hih_i, and the fraction mim_i of them that miss pays Pi+1P_{i+1} on top; averaging, Pi=hi+miPi+1P_i = h_i + m_i P_{i+1}. Every access reaches level 1, so AMAT=P1\mathrm{AMAT} = P_1, and unfolding the recurrence from P1P_1 to Pk+1=TP_{k+1} = T gives the formula. ∎

With the plateaus of Output 12.2 rounded to 1, 4, 20 and 150 ns, the extra times are h1=1h_1 = 1, h2=3h_2 = 3, h3=16h_3 = 16 and T=130T = 130 ns. For local miss ratios of 5 %, 20 % and 30 %:

AMAT=1+0.05 (3+0.2 (16+0.3×130))=1+0.05 (3+0.2×55)=1.7 ns.\mathrm{AMAT} = 1 + 0.05\,\bigl(3 + 0.2\,(16 + 0.3 \times 130)\bigr) = 1 + 0.05\,(3 + 0.2 \times 55) = 1.7\ \text{ns}.

Without any cache every access would take 150 ns, about ninety times longer. The formula also tells where to work: halving m1m_1 saves 0.350.35 ns here, about as much as removing the trip to main memory altogether (T=0T = 0 saves 0.390.39 ns), and more than twice what removing the L3’s own extra time h3h_3 would (0.160.16 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.

128/16=8128 / 16 = 8 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")
Listing 12.11. The index from the wrong bits code/bachelor-2/12-caches/listings/exo_wrong_bits.py
$ python exo_wrong_bits.py
Cache       240 hits   16 misses
WrongCache  224 hits   32 misses
Output 12.9. Correct and wrong mapping.
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)
Writes still owed by a write-back cache code/bachelor-2/12-caches/exercises/flush.py

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.

32 768/(8×64)=6432\,768 / (8 \times 64) = 64 sets: 6 offset bits, 6 index bits, 32−12=2032 - 12 = 20 tag bits. The L2 of Output 12.8 has 2 097 152/(16×64)=20482\,097\,152 / (16 \times 64) = 2048 sets: 6 offset bits, 11 index bits, and with 32-bit addresses 32−17=1532 - 17 = 15 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 (0x84=1000 01002\texttt{0x84} = 1000\,0100_2), with tags 0, 2, 0, 4, 2, 1, 0, 6, 0. Set 0, least recently used first: [0][0], [0,2][0, 2], [2,0][2, 0] (hit), [0,4][0, 4], [4,2][4, 2], [2,1][2, 1], [1,0][1, 0], [0,6][0, 6], [6,0][6, 0] (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];
    }
}
Listing 12.12. Column sums, column by column code/bachelor-2/12-caches/listings/exo_colsums.c
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];
}
Column sums, row by row code/bachelor-2/12-caches/listings/exo_colsums.c
$ 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
Output 12.13. One run on the author’s laptop, 8192×40968192 \times 4096 grid.

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
Classifying misses with a shadow cache code/bachelor-2/12-caches/listings/three_c.py

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 C+2C + 2 lines? Over CC lines?

Solution

Solution of Exercise 12.8.

First, a fully associative LRU cache of CC lines always holds the (at most CC) 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 CC it held, which is the one that is no longer among the CC most recent. Now let access tt be to ℓt mod (C+1)\ell_{t \bmod (C+1)}. For t≤Ct \le C, the line is used for the first time: a miss. For t>Ct > C, the accesses t−C,…,t−1t - C, \dots, t - 1 are to CC distinct lines, all different from ℓt mod (C+1)\ell_{t \bmod (C+1)}, since any C+1C + 1 consecutive accesses of the sweep are to distinct lines. The cache holds exactly those CC lines, so access tt misses. Over C+2C + 2 lines, or any number more than CC, the same argument applies: the last CC accesses are to CC distinct lines other than the requested one. Over CC lines, the first CC accesses miss and all others hit, since the whole sweep fits.

Exercise 12.9 ★★

A transpose writes bji=aijb_{ji} = a_{ij}. 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];
}
Listing 12.13. The plain transpose of an 8192×81928192 \times 8192 matrix of int code/bachelor-2/12-caches/listings/transpose.c
Solution

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];
}
The tiled transpose code/bachelor-2/12-caches/listings/transpose.c
$ 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
Output 12.14. One run on the author’s laptop, 8192×81928192 \times 8192 int.

The plain version reads aa by rows but writes bb by columns, 32 KiB apart: every write is to a new line, and with 8192 rows, each line of bb 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 t×tt \times t uses tt lines of aa and tt lines of bb, each reused tt 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 (64×6464 \times 64 bytes), so all the lines of a tile’s column of bb 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, C=N=32C = N = 32, yet the column order misses every time. Generalise: for an N×NN \times N matrix of 4-byte words, NN a power of two at least 8, read in column order through a direct-mapped cache of CC lines of BB bytes, with CC and BB powers of two, B≤4NB \le 4N, 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 4N4N bytes, that is by s=4N/Bs = 4N / B lines, and the line of row ii has index (is+c) mod C(i s + c) \bmod C for a constant cc. If s≥Cs \ge C, every row of the column falls in the same set; otherwise the column visits C/sC / s sets in turn (all powers of two). So a column uses u=min⁡(N,max⁡(1,CB/(4N)))u = \min(N, \max(1, C B / (4N))) sets. The line of (i,j)(i, j) is next needed at (i,j+1)(i, j + 1), which lies in the same line when B≥8B \ge 8. Between the two accesses, the column order reads rows i+1,…,N−1i + 1, \dots, N - 1 of column jj and rows 0,…,i−10, \dots, i - 1 of column j+1j + 1. If u<Nu < N, rows i+ui + u or i−ui - u (one of them exists, since u≤N/2u \le N / 2) share the set of row ii, and their line, read in between, evicts it: every read misses. If u=Nu = N, every row has its own set, and the column order misses only on the 4N2/B4N^2 / B first uses. Now u=Nu = N means CB≥4N2C B \ge 4N^2: the cache must be as large as the whole matrix. For the chapter’s example, CB=1C B = 1 KiB and 4N2=44N^2 = 4 KiB, so every read misses. A fully associative cache needs only C≥NC \ge N lines (Proposition 12.12), one column’s worth: the direct mapping costs a factor 4N/B4N / B in size on this access pattern.

Exercise 12.11 ★★★

The simulator below counts the misses of a tiled transpose of a 128×128128 \times 128 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
Listing 12.14. The misses of one tile size code/bachelor-2/12-caches/listings/exo_block_size.py
$ 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
Output 12.10. Misses by tile size; tile 1 is the plain transpose.
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
Output 12.15. The same misses, split by the classifier of Exercise 12.7.

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: aa is read by rows (1024 misses, one per line) and bb written by columns, each column touching 128 lines, more than the cache holds, so every write misses: 1024+16 384=17 4081024 + 16\,384 = 17\,408. With tiles of t≤8t \le 8, the writes into one line of bb come tt at a time, and the misses of bb fall to about 16 384/t16\,384 / t: 9216=1024+81929216 = 1024 + 8192 for t=2t = 2. For t=4t = 4 and 8, the lines of a tile of aa and of the matching tile of bb fall in the same sets for some tiles, and the classifier finds 288, then 1824 conflict misses. At t=16t = 16 a tile’s column of bb 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: 2×65 536/64=20482 \times 65\,536 / 64 = 2048, 0.1250.125 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, AMAT=1+0.05×100=6\mathrm{AMAT} = 1 + 0.05 \times 100 = 6 ns. With an L2 of local miss ratio m2m_2, AMAT=1+0.05 (4+100 m2)\mathrm{AMAT} = 1 + 0.05\,(4 + 100\,m_2), lower than 6 if and only if 4+100 m2<1004 + 100\,m_2 < 100, that is m2<0.96m_2 < 0.96: the L2 pays for itself as soon as it catches more than 4 % of the L1’s misses. With m2=0.25m_2 = 0.25, AMAT=1+0.05×29=2.45\mathrm{AMAT} = 1 + 0.05 \times 29 = 2.45 ns. Adding an L3 replaces the term 100 m2100\,m_2 by m2(15+100 m3)m_2(15 + 100\,m_3), lower if and only if m3<0.85m_3 < 0.85. With m3=0.4m_3 = 0.4: AMAT=1+0.05 (4+0.25 (15+40))=1+0.05×17.75=1.8875\mathrm{AMAT} = 1 + 0.05\,(4 + 0.25\,(15 + 40)) = 1 + 0.05 \times 17.75 = 1.8875 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 3×33 \times 3 pixels around it. The image is a square of N×NN \times N 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);
}
Listing 12.15. One pixel of the blur, and two traversal orders code/bachelor-2/12-caches/listings/blur.c

Part I — Counting by hand.

  1. How many reads of the input does the blur of an N×NN \times N image perform? Give the number for N=256N = 256.
  2. In row order, which input rows does the computation of output row yy read? Which of them were read for row y−1y - 1?
  3. Show that if the cache holds three rows of the image, every line of the input misses exactly once in row order.
  4. Deduce that the row order misses once every 16 pixels: a miss ratio of 1/161/16 per pixel of the image, and 1/1441/144 per read.
  5. For N=256N = 256 and a 4 KiB cache, how many lines does a row take, and do three rows fit?
  6. 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
Listing 12.16. The reads of the blur through a 4 KiB 4-way cache code/bachelor-2/12-caches/listings/blur_sim.py
$ 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
Output 12.11. The misses of four traversal orders, N=256N = 256; the last column divides by the 2542254^2 output pixels.
  1. Check the number of reads.
  2. Explain the 4096 misses of the row order exactly, and why the last column gives 0.06350.0635 and not 1/161/16.
  3. In column order, show that each new output pixel brings one new line, except where x−1x - 1 and x+1x + 1 fall in different lines from xx. Deduce about 1+2/161 + 2/16 misses per pixel, and compare with 1.12691.1269.
  4. Which kind of misses, in the sense of Definition 12.10, are those of the column order?
  5. Would a fully associative cache of 4 KiB do better in column order? Use Proposition 12.12.
  6. 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 ww 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);
}
Listing 12.17. The blur by strips of ww columns code/bachelor-2/12-caches/listings/blur.c
  1. For w=16w = 16 with strips aligned on lines, how many lines does one row of a strip read?
  2. Deduce the misses of the strips of 16 as a function of NN, and check the simulator’s 11 776.
  3. Do the same for w=64w = 64, and explain why the simulator finds 0.08730.0873 per pixel.
  4. Give the misses per pixel of strips of ww columns, ww a multiple of 16, when the cache holds three rows of a strip, and their limit as ww grows.
  5. How many lines must the cache hold for three rows of a strip of ww? 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?
  6. 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
Output 12.12. One run on the author’s laptop: the blur of a 4096×40964096 \times 4096 generated image in four orders.
  1. For N=4096N = 4096, how many KiB does a row take? Do three rows fit in the laptop’s L1 of 48 KiB? A column’s lines?
  2. 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?
  3. Explain the gap between the two ratios with the hierarchy of Section 12.1: which level serves the column order’s misses?
  4. 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?
  5. 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.
  6. State the result of the problem.
Solution

Solution of Problem 12.1.

1. Nine reads per output pixel, and (N−2)2(N - 2)^2 output pixels: 9(N−2)29(N - 2)^2, that is 9×2542=580 6449 \times 254^2 = 580\,644 for N=256N = 256.

2. Rows y−1y - 1, yy and y+1y + 1. Row y−1y - 1 read rows y−2y - 2, y−1y - 1 and yy: two of the three were already read.

3. A line of input row rr is read for output rows r−1r - 1, rr and r+1r + 1, three consecutive rows. Between two consecutive uses, at output pixel xx of one row and output pixel xx of the next, the blur reads, at each column position, three lines: those of three rows to the right of xx 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 N2/16N^2 / 16 misses for N2N^2 pixels of the image: one every 16 pixels, a miss ratio of 1/161/16 per pixel; since each pixel is read about nine times, 1/1441/144 per read.

5. A row is 256×4=1024256 \times 4 = 1024 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 NN rows: at least one line per row, 256 lines, and two per row where x−1x - 1 or x+1x + 1 is in another line. The cache has 64 lines: the lines of the first rows are gone when the next column needs them.

7. 9×2542=580 6449 \times 254^2 = 580\,644, the simulator’s figure.

8. The image is 2562×4/64=4096256^2 \times 4 / 64 = 4096 lines, and the row order misses once on each, by question 3. The last column divides by the 2542254^2 output pixels, not by the 2562256^2 pixels read: 4096/64 516=0.06354096 / 64\,516 = 0.0635, against 4096/65 536=1/164096 / 65\,536 = 1/16.

9. Output pixel (y,x)(y, x) comes after (y−1,x)(y - 1, x), which read rows y−2y - 2 to yy; the lines of rows y−1y - 1 and yy are still in cache, and those of row y+1y + 1 are new. That is one line if x−1x - 1, xx and x+1x + 1 are in the same line, that is x mod 16∉{0,15}x \bmod 16 \notin \{0, 15\}, and two otherwise: on average 1+2/16=1.1251 + 2/16 = 1.125 misses per pixel. Exactly: each of the 224 columns of the first kind misses 3+253=2563 + 253 = 256 times (three rows at y=1y = 1, then one per row), each of the 30 others 512 times: 224×256+30×512=72 704224 \times 256 + 30 \times 512 = 72\,704, the simulator’s count, and 72 704/64 516=1.126972\,704 / 64\,516 = 1.1269.

10. 4096 of them are compulsory, the first use of each line. The others are capacity misses: the line of (y,x)(y, x) 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 C≥NC \ge N, 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 x0−1x_0 - 1 and x0+16x_0 + 16.

14. 3N3N misses per strip, N/16N / 16 strips, less the missing left neighbour of the first strip and right neighbour of the last, NN lines each: 3N2/16−2N=12 288−512=11 7763N^2/16 - 2N = 12\,288 - 512 = 11\,776.

15. Six lines per row of a strip of 64 (four of its own, two neighbours): 6N×N/64−2N=6144−512=56326N \times N/64 - 2N = 6144 - 512 = 5632, and 5632/64 516=0.08735632 / 64\,516 = 0.0873.

16. (w/16+2)N(w/16 + 2) N misses per strip of wNw N pixels, so (w/16+2)/w=1/16+2/w(w/16 + 2)/w = 1/16 + 2/w per pixel, which tends to 1/161/16, the row order’s ratio, as ww grows.

17. Three rows of the strip need 3(w/16+2)3(w/16 + 2) lines; with 64 lines, w/16+2≤21w/16 + 2 \le 21, so w≤304w \le 304. But rows 16 lines apart start in the same set: the w/16+2w/16 + 2 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 w/16+2=16w/16 + 2 = 16, w=224w = 224 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, 3/163/16 per pixel; a strip of 64 two for four, 6/646/64.

19. 4096×4=164096 \times 4 = 16 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. 72 704/4096≈17.872\,704 / 4096 \approx 17.8 times more misses; measured, 483.7/53.7≈9.0483.7 / 53.7 \approx 9.0 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: 0.0635<0.0873<0.1825<1.12690.0635 < 0.0873 < 0.1825 < 1.1269. The order is the same.

23. 40942≈16.84094^2 \approx 16.8 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 1.1251.125 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 1/161/16, the least any order can reach; the column order misses more than once per pixel (1.1271.127 in the simulator, about eighteen times more), strips of ww columns sit between at 1/16+2/w1/16 + 2/w; 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.

本章定义的术语

在术语表中查看全部 1050 个术语