Sub topic 3
Measuring Cache Behavior Without Fooling Yourself
Assume you know arrays, pointers, structs, threads, and Big-O notation. You also need basic command-line skills and a compiler.
Measure Before Optimizing
A cache benchmark must control unrelated effects. Use an optimized build, repeat each test, warm up the data, prevent the compiler from removing the work, and compare the same amount of useful work. Report the median rather than one timing.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
const size_t n = 64 * 1024 * 1024;
int *a = malloc(n * sizeof *a);
if (!a) return 1;
for (size_t i = 0; i < n; ++i) a[i] = (int)i;
for (size_t stride = 1; stride <= 1024; stride *= 16) {
volatile long long sum = 0;
clock_t start = clock();
for (size_t i = 0; i < n; i += stride)
sum += a[i];
double seconds = (double)(clock() - start) / CLOCKS_PER_SEC;
printf("stride=%zu time=%.3f sum=%lld\n", stride, seconds, sum);
}
free(a);
}Use hardware counters when possible, such as Linux perf stat. Check cache misses, instructions, and cycles together. A faster result may simply perform less work.
| Pattern | Likely effect |
|---|---|
| Sequential access | Good spatial locality and prefetching |
| Large regular stride | More cache and TLB misses |
| Repeated access to a small region | Good temporal locality |
Associativity and Conflict Misses
A cache has a limited number of slots in each set. A power-of-two stride can repeatedly map accesses to the same sets, evicting useful lines even when the cache has enough total capacity. Test several nearby strides, not only powers of two.
Blocking Matrix Loops
For matrix multiplication, transpose, or image processing, process small tiles that fit in cache. A tile reuses rows and columns before they are evicted. Choose the tile size experimentally because cache levels, element sizes, and associativity matter.
Cache-Friendly Containers
Open-addressing hash tables keep entries in one array. Probing nearby slots usually has good locality, but high load factors increase probes. Chained tables follow pointers to separate nodes, so collisions are flexible but often cause cache misses.
B-trees store many sorted keys in one wide node. One node visit examines several keys after loading one cache line or page. A binary tree usually follows a pointer for every comparison, making it slower in memory even when both operations are logarithmic.
False Sharing Between Threads
False sharing occurs when independent variables share one cache line. Updates by different cores invalidate that line repeatedly. Separate hot counters with padding or alignment, then verify the change with a multithreaded benchmark. Do not assume 64 bytes on every target system.
TLB and Page Locality
The translation lookaside buffer (TLB) caches virtual-to-physical page translations. Touching one byte on many pages can miss in the TLB even when cache capacity is sufficient. Contiguous storage, fewer allocations, and suitable huge pages can help.
Cache-Oblivious Layouts
Cache-oblivious algorithms recursively divide data without choosing a cache size. Recursive subproblems eventually fit in every cache level, often improving locality across machines. They can add recursion overhead and are not automatically faster than tuned blocking.
Exercise
Why can a linked-list traversal be slower than an array traversal with the same O(n) complexity?
Show answer
List nodes may be scattered, causing pointer-dependent cache and TLB misses. Array elements are adjacent and easier for caches and prefetchers to load.