Sub topic 3
Spatial and Temporal Locality
This chapter assumes you can read C, know what arrays, structs, and pointers are, and have seen the idea of a cache line from the previous chapter. Locality is the property of a program that lets caches work. A cache can only help if the program reuses data it touched recently, or touches data near what it touched recently. Those two behaviors have names: temporal locality and spatial locality.
The two kinds of locality
Temporal locality means that a location accessed now is likely to be accessed again soon. The cache keeps recently used lines, so the second access hits instead of going to main memory.
Spatial locality means that after accessing a location, the program is likely to access nearby addresses soon. This works because a miss loads a whole cache line (commonly 64 bytes), not one value. The neighbors arrive for free.
| Property | What the program does | What the hardware supplies |
|---|---|---|
| Temporal locality | Reuses the same address within a short time | Keeps the line in cache until it is evicted |
| Spatial locality | Uses addresses close to one another | Loads a whole line per miss, and prefetchers fetch ahead |
The two are independent. A program can have one without the other, and the best code has both.
Spotting locality in code
Read a loop and ask two questions for every memory access. First, is this address near the previous one? Second, will this address be used again before many other bytes are touched?
#include <stddef.h>
long sum_and_scale(const int *values, size_t n, long *total) {
long s = 0;
for (size_t i = 0; i < n; i++) {
s += values[i]; /* spatial: values[i+1] is adjacent */
*total += s; /* temporal: same address every iteration */
}
return s;
}In this loop:
values[i]has strong spatial locality. With 4-byteintand 64-byte lines, one miss serves 16 consecutive elements. It has no temporal locality, because each element is read once.*totalhas strong temporal locality. The same address is used on every iteration, so after the first access it stays in cache (or in a register, if the compiler can prove no aliasing).sandiare local variables. They usually live in registers, which is the extreme form of temporal locality.
Streaming over a huge array once is the classic case of spatial locality without temporal locality. Each line is loaded, used, and never needed again.
Counting misses for a sequential scan
Spatial locality can be turned into a number. For a sequential scan with element size s bytes and line size L bytes, one miss in every L / s accesses is expected, assuming the array start is line-aligned and nothing else interferes.
For 8-byte double and 64-byte lines, that is 1/8, or 12.5% of accesses missing. For a stride of 64 bytes or more, every access touches a new line, so the miss rate rises to 100% on a cold array. The next chapter looks at strides in detail. Here the point is that the same count of instructions can produce an eight-fold difference in lines fetched.
The diagram below shows how one miss turns into several hits when accesses are adjacent.
Temporal locality and working set size
Temporal locality only pays off if the data survives in cache until the next use. The data a loop touches between two uses of the same address is its reuse distance, measured in distinct cache lines. If the reuse distance is smaller than the cache can hold, the second access hits. If it is larger, the line has been evicted and the access misses again.
The set of lines a phase of the program actively uses is its working set. This gives a practical rule: temporal locality is real only when the working set fits in the cache level you are targeting.
Consider summing the same array twice:
#include <stddef.h>
long two_passes(const int *a, size_t n) {
long s = 0;
for (size_t i = 0; i < n; i++) s += a[i]; /* pass 1 */
for (size_t i = 0; i < n; i++) s += a[i]; /* pass 2 */
return s;
}If n * sizeof(int) is 16 KB, the second pass finds everything in a typical 32 KB L1 data cache. If it is 512 MB, the first elements were evicted long before pass 2 reaches them, and both passes stream from main memory. The code is identical. Only the data size changed.
A fused version restores temporal locality by using each element twice while it is still cached:
#include <stddef.h>
long fused(const int *a, size_t n) {
long s = 0;
for (size_t i = 0; i < n; i++) {
s += a[i];
s += a[i]; /* reused immediately; a[i] is in a register */
}
return s;
}This example is artificial, because the two passes compute the same thing. Real programs follow the same pattern when they run several different transformations over one large array. Merging the passes (loop fusion) cuts the number of times each line is loaded from memory.
Both kinds in one structure
Look at a hash table lookup, a common mix. The bucket array is accessed at pseudo-random positions, so successive lookups have poor spatial locality. A hot table that fits in cache still has good temporal locality, because the same buckets are reused. A table far larger than cache has neither, and every lookup costs a miss.
Compare that with a binary search over a sorted array. The first few probes, near the middle and the quarter points, are the same for every search. These lines stay in cache (temporal locality). The last few probes land within one or two lines (spatial locality). The probes in between are the expensive ones.
Common mistakes
- Assuming Big-O predicts speed. Two loops with the same operation count can differ several times in run time when one misses on every access.
- Confusing "used again" with "used again soon." Reuse after the working set has exceeded the cache gives no benefit.
- Counting only your own data. Other threads, the operating system, and other arrays in the same loop compete for the same cache.
- Claiming spatial locality from array indexing alone. The index pattern matters.
a[i * 1024]indexes an array and still touches a new line every time. - Treating a register as a cache question. If the compiler keeps a value in a register, there is no memory access to analyze. Check the generated assembly before reasoning about a variable.
Summary of the working model
- A miss loads a full line, so nearby data is cheap. That is spatial locality.
- A line that stays in cache makes repeat access cheap. That is temporal locality.
- Reuse works only while the working set fits in the cache.
- To improve locality, either bring accesses closer in space (better layout and traversal) or closer in time (fusion and blocking). The later chapters on traversal order, struct layout, and tiling apply these two moves.
Exercise
A function loops over a 64 MB array of 4-byte ints and sums it, then immediately loops over it again to find the maximum. Assuming 64-byte lines and a 1 MB last-level cache, (a) how many cache misses per element does one pass incur in the best case, and (b) does the second pass benefit from temporal locality? What change would help?
Show answer
(a) One miss per 16 elements (64 / 4), so 1/16 = 0.0625 misses per element, thanks to spatial locality. (b) No. The array is 64 MB and the cache is 1 MB, so the early lines are evicted before the second pass reaches them, and the second pass misses at the same rate as the first. Fusing the two loops into one, computing the sum and the maximum together in a single pass, loads each line once and uses it for both results.
Exercise
In the function sum_and_scale earlier in this chapter, which access shows temporal locality but little spatial locality, and which shows spatial locality but little temporal locality?
Show answer
*total shows temporal locality, because the same address is used on every iteration, but it has no spatial pattern since it is a single address. values[i] shows spatial locality, because consecutive elements share cache lines, but little temporal locality, because each element is read only once.