Description

AMAT = hit time + miss rate × miss penalty, so every optimization attacks one of four targets: reduce hit time, increase bandwidth, reduce miss penalty, or reduce miss rate (some also save power).

#OptimizationPrimary goalIdea
1Small and simple L1 cachesHit time, powerSmall, low-associativity L1 keeps the critical path short; L1 is the smallest, fastest cache closest to the CPU
2Way predictionHit timePredict which way of a set will hit and read only that way first; a wrong guess costs an extra cycle
3Pipelined cache accessBandwidthSpread an L1 access over several stages so the clock stays fast and accesses overlap
4Non-blocking cacheMiss penalty, bandwidthLet hits (and further misses) proceed while a miss is outstanding ("hit under miss", "miss under miss"); tracked in MSHRs
5Multibanked cacheBandwidthSplit the cache into banks (often interleaved by block address) so several accesses proceed in parallel
6Critical word first / early restartMiss penaltyFetch the needed word first and restart the CPU as soon as it arrives, finishing the block fill in the background
7Merging write bufferMiss penaltyCombine writes to the same block in the write buffer into one wider write
8Compiler optimizationsMiss rateLoop interchange, loop blocking (tiling), loop fusion to improve locality
9Hardware prefetchingMiss penalty / rateHardware detects streams (e.g. sequential or strided) and fetches blocks ahead of use
10Compiler-controlled prefetchingMiss penalty / rateCompiler inserts prefetch instructions ahead of loads

Other techniques:

  • Split cache: separate instruction and data caches (parallel access, no structural conflict).
  • Victim cache: tiny cache holding recently evicted blocks to catch conflict misses (Jouppi 1990).
  • Higher associativity: cuts conflict misses.
  • Multi-level caching: L1/L2/L3 balance speed and cost.
  • Cache bypassing: skip the cache for streaming data to avoid pollution.
  • HBM / L4: high-bandwidth stacked DRAM acts as a large, fast cache between on-chip caches and DRAM.

Key Formulas

AMAT = Hit time + Miss rate × Miss penalty

Bank selection:         bank = (block address) mod (number of banks)

Loop blocking:          need 3 · B² · (element size) ≤ cache size
                        → B ≤ sqrt( cache size / (3 · element size) )
Matrix multiply, words moved:   naive ≈ 2N³ + N²,    blocked ≈ 2N³/B + N²

Prefetch usefulness:    accuracy = useful prefetches / prefetches issued
                        coverage = misses removed / misses without prefetching

Steps

Loop interchange: (1) identify the inner loop's access stride, (2) if it jumps across rows in a row-major array, swap the loop order so the inner loop walks consecutive addresses.

Loop blocking: (1) pick tile size B so the working tiles fit in cache, (2) add outer loops over tiles, (3) compute within each tile.

Critical word first: (1) miss occurs, (2) memory returns the requested word first, (3) CPU resumes (early restart), (4) the rest of the block fills in.

Worked Example

A. Loop interchange. Array x[N][N] of 4-byte ints in C (row-major), cache 4 KB direct-mapped, 64 B blocks, N = 64 (the array is 16 KB).

  • Row-order inner loop (x[i][j], j inner): 256 misses (16 ints per block → 4096 / 16).
  • Column-order inner loop (x[i][j], i inner): 4096 misses, every access misses.

Interchange gives 16× fewer misses with no change in results.

B. Tile size. 32 KB cache, 8-byte doubles: B ≤ sqrt(32768 / (3 × 8)) = sqrt(1365) ≈ 36.9 → choose B = 32.

C. Blocked matrix multiply traffic. N = 1024, B = 32: naive ≈ 2N³ words; blocked ≈ 2N³/32, a 32× reduction in words moved between memory and cache (ignoring the N² term).

D. Critical word first. 64 B block = 8 words. First word arrives after 50 ns, then one word every 10 ns.

  • Wait for whole block: 50 + 7 × 10 = 120 ns.
  • Critical word first + early restart: 50 ns (CPU continues while the rest arrives), saving 70 ns.

E. Banking. 4 banks, block-interleaved: blocks 0, 1, 2, 3 go to banks 0, 1, 2, 3 and can be accessed simultaneously, while blocks 0 and 4 collide on bank 0.

F. Write buffer merging. Four 8-byte writes to consecutive addresses of one 32 B block: without merging use four buffer entries and four memory writes; with merging one entry, one write.

G. Victim cache. Direct-mapped cache, two blocks A and B alternately accessed that map to the same line. Without a victim cache every access misses; with a one-entry victim cache they swap and hit after the first two misses.

Python / Assembly

def misses(addrs, cache_bytes, block, assoc):
    sets = (cache_bytes // block) // assoc
    cache = [[] for _ in range(sets)]
    m = 0
    for a in addrs:
        b = a // block; s = b % sets
        if b in cache[s]:
            cache[s].remove(b); cache[s].append(b)
        else:
            m += 1
            if len(cache[s]) == assoc: cache[s].pop(0)
            cache[s].append(b)
    return m

N, E = 64, 4
row = [(i*N + j)*E for i in range(N) for j in range(N)]
col = [(i*N + j)*E for j in range(N) for i in range(N)]
print(misses(row, 4096, 64, 1), misses(col, 4096, 64, 1))    # 256 4096

Blocked matrix multiply in C (the compiler optimization to know):

for (int jj = 0; jj < N; jj += B)
  for (int kk = 0; kk < N; kk += B)
    for (int i = 0; i < N; i++)
      for (int j = jj; j < min(jj+B, N); j++) {
        double r = 0;
        for (int k = kk; k < min(kk+B, N); k++)
          r += y[i][k] * z[k][j];
        x[i][j] += r;
      }

Software prefetch (x86-64 and RISC-V Zicbop extension):

prefetcht0 [rsi + 256]        # x86-64: bring the line 256 bytes ahead into all cache levels
# RISC-V (Zicbop):  prefetch.r 256(a0)

Notes

  • Strip mining: sometimes listed next to loop unrolling; it appears with vector code (splitting a long loop into pieces that fit the vector length, Topic 12) and, loosely, as blocking for caches.
  • Non-blocking caches only help out-of-order or multi-issue cores that can keep doing useful work during a miss.
  • Prefetching can hurt: wrong guesses waste bandwidth and evict useful data (pollution).
  • Way prediction saves energy because only one way is read.
  • Quick facts: cache blocking reduces misses in matrix operations; write buffer reduces write delays; victim cache reduces conflict misses; compiler optimizations rearrange code for locality; cache bypassing avoids pollution.

References: [HP6] Ch. 2 (2.3 "Ten Advanced Optimizations of Cache Performance"), Appendix B (B.3); Jouppi, "Improving Direct-Mapped Cache Performance by the Addition of a Small Fully-Associative Cache and Prefetch Buffers," ISCA 1990; [PH-RV] Ch. 5 (5.4, 5.14 on blocking);