Sub topic 18
Cache-oblivious algorithms and layouts
This chapter assumes you have read the earlier chapters on cache lines, traversal order, and blocking (tiling). You should be comfortable with recursion and with reading C.
The problem with tuned blocking
Blocking works, but the tile size B is a tuning parameter. The best value depends on the cache size, the line size, and how many arrays share the cache. A tile that fits L1 on one machine may thrash it on another. Code tuned for one level of the hierarchy also ignores the others, such as L2, L3, and the TLB.
A cache-oblivious algorithm avoids this. It never mentions the cache size M or line size L. Instead it divides the problem recursively until the pieces are small. At some depth, a piece fits in each level of the hierarchy, whatever that level's size is. The idea comes from Frigo, Leiserson, Prokop, and Ramachandran (1999).
The model and its assumptions
The analysis uses an idealized two-level machine. It has a cache of M words, transfers in lines of L words, and uses optimal replacement. Real caches use LRU-like policies and limited associativity. The cost of LRU is only a constant factor, so the results still carry over.
Many results also need the tall-cache assumption, M = Ω(L²). The cache must hold at least L lines, each of L words. Typical hardware satisfies this. A 32 KiB L1 with 64-byte lines holds 512 lines, and a square tile of 8-byte doubles needs only 8 lines.
Under these assumptions, a recursive transpose of an n × n matrix costs O(1 + n²/L) misses. That is the same bound as a well-tuned blocked version.
Recursive transpose
The recursion splits the longer dimension in half. It stops when the piece is small. The cutoff only limits function-call overhead. It is not a cache parameter, so the algorithm stays correct and cache-efficient if it is wrong.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define CUTOFF 16
/* Transposes src[r0..r1) x [c0..c1) into dst. n is the row length of both matrices. */
static void transpose_rec(double *dst, const double *src, size_t n,
size_t r0, size_t r1, size_t c0, size_t c1) {
size_t rows = r1 - r0, cols = c1 - c0;
if (rows <= CUTOFF && cols <= CUTOFF) {
for (size_t i = r0; i < r1; i++)
for (size_t j = c0; j < c1; j++)
dst[j * n + i] = src[i * n + j];
} else if (rows >= cols) {
size_t mid = r0 + rows / 2;
transpose_rec(dst, src, n, r0, mid, c0, c1);
transpose_rec(dst, src, n, mid, r1, c0, c1);
} else {
size_t mid = c0 + cols / 2;
transpose_rec(dst, src, n, r0, r1, c0, mid);
transpose_rec(dst, src, n, r0, r1, mid, c1);
}
}
int main(void) {
size_t n = 1000;
double *src = malloc(n * n * sizeof *src);
double *dst = malloc(n * n * sizeof *dst);
if (!src || !dst) return 1;
for (size_t i = 0; i < n * n; i++) src[i] = (double)i;
transpose_rec(dst, src, n, 0, n, 0, n);
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++)
if (dst[j * n + i] != src[i * n + j]) {
puts("mismatch");
return 1;
}
puts("ok");
free(src);
free(dst);
return 0;
}Compare this with transpose_blocked from the blocking chapter. That version needs B chosen by hand. This one has a cutoff that only needs to be "small enough to amortize call overhead".
Why recursion adapts to every level
The diagram shows the recursion as a tree. Each level halves a dimension. For any cache level, some depth of the tree has subproblems that fit in that level.
Once a subproblem fits in a cache level, all its remaining work hits that level. Misses occur only when the subproblem is first loaded. The same argument applies at each level and to the TLB, with no tuning.
Cache-oblivious layouts
Algorithms are one half. Layouts are the other. A row-major array favors one traversal direction, but a recursive layout keeps nearby elements in two dimensions close in memory.
Z-order (Morton order)
Z-order interleaves the bits of the row and column indices. Cells that are close in 2D tend to be close in the 1D index.
#include <stdint.h>
#include <stdio.h>
static uint32_t spread(uint32_t x) {
x &= 0xFFFF;
x = (x | (x << 8)) & 0x00FF00FFu;
x = (x | (x << 4)) & 0x0F0F0F0Fu;
x = (x | (x << 2)) & 0x33333333u;
x = (x | (x << 1)) & 0x55555555u;
return x;
}
static uint32_t morton(uint32_t x, uint32_t y) {
return spread(x) | (spread(y) << 1);
}
int main(void) {
for (uint32_t y = 0; y < 4; y++) {
for (uint32_t x = 0; x < 4; x++)
printf("%3u", morton(x, y));
putchar('\n');
}
return 0;
}The program prints a 4×4 grid whose rows are 0 1 4 5, 2 3 6 7, 8 9 12 13, and 10 11 14 15. Each 2×2 block holds four consecutive indices, and each 4×4 block holds sixteen. Z-order has no tile-size parameter.
The costs are real. Index computation is more expensive than i * n + j, though hardware bit-interleave instructions (PDEP on x86 with BMI2) help. Row scans are no longer contiguous. Z-order helps most when you access the data in both dimensions, as in stencils, image processing, and spatial queries. Matrices whose sides are not powers of two need padding or a hybrid layout, for example Z-ordered tiles with row-major data inside each tile.
van Emde Boas layout for trees
A binary search tree stored in sorted or breadth-first order has poor locality. A search touches log₂ n nodes, and below the top few levels almost every one is a separate cache line. The van Emde Boas (vEB) layout stores the tree recursively:
- Cut the tree at half its height. This gives a top subtree and several bottom subtrees.
- Store the top subtree contiguously, using the same layout recursively.
- Store each bottom subtree contiguously after it, also recursively.
A search then costs O(log_L n) cache misses, matching a B-tree with the right node size, without knowing L. This is the same result as the wide-node trees chapter, reached without a fixed node width.
| Approach | Needs `B` or `L` known? | Matches multiple cache levels? | Typical cost |
|---|---|---|---|
| Naive loops | No | No | Many misses |
| Blocking or B-tree nodes | Yes | One level per tuning | Best on the tuned machine |
| Cache-oblivious | No | Yes, in theory | Constant-factor overhead |
Gotchas
- Recursion overhead. Recursing to single elements spends more time on calls than on work. Always use a base-case cutoff and measure it.
- Constant factors. The asymptotic miss count can match blocking while the running time is worse. Index arithmetic, branches, and call overhead are not in the model.
- Associativity. The model assumes a fully associative cache. Power-of-two sizes and strides can still cause conflict misses. Padding rows is often still needed.
- Prefetching. Hardware prefetchers favor simple strides. Recursive access patterns look less regular, so prefetching may help less than it does for a plain scan.
- Write-heavy code. Layout transformations cost a pass over the data. Convert once, then reuse, or the conversion cancels the benefit.
- Measure. Use the counters from the measurement chapter, and compare against a tuned blocked version on your real hardware.
Exercise
A colleague replaces a row-major 2D grid with a Z-order layout. Their workload scans each row from left to right, one row at a time. Will this likely help? Name one workload where it would.
Show answer
It will likely hurt. A row scan in row-major order is a contiguous sequential pass that uses every byte of each cache line and is easy to prefetch. In Z-order, the elements of a row are spread across the array, and each index needs a bit-interleave computation. Z-order helps when accesses are local in both dimensions, for example a 2D stencil that reads each cell's neighbors above and below, or spatial queries on image tiles.
Exercise
In transpose_rec, why does the algorithm split the longer dimension, and what does CUTOFF control?
Show answer
Splitting the longer dimension keeps the pieces close to square, and square pieces use the most cache lines for the least perimeter. This is what lets a piece fit in a cache level with both its source and destination lines. CUTOFF only decides when to stop recursing so function-call overhead does not dominate. It is not a cache size, so a poor value changes speed but not correctness or the asymptotic miss count.