Sub topic 2
Temporal and spatial locality
This chapter assumes you know what a cache is at a high level (a small, fast memory between the CPU and main memory). It also assumes you are comfortable with byte addresses, powers of two, and weighted averages. The chapter explains the property of programs that makes caches work. Later chapters cover how a cache is built.
Why locality matters
A cache is much smaller than main memory. If a program touched addresses at random, the cache would hold the wrong data almost every time, and the hierarchy would not speed anything up. Caches help because real programs do not access memory at random. They reuse data they just touched, and they touch data near what they just touched. This property is the principle of locality. It has two forms.
Temporal locality
Temporal locality means that an address accessed now is likely to be accessed again soon.
Typical sources:
- Loop control variables, accumulators and counters, read and written on every iteration.
- Instructions inside a loop body, fetched again on every iteration.
- The top of the stack, which is reused as functions are called and return.
- A lookup table or small array consulted many times.
The cache exploits temporal locality by keeping recently used blocks. Once a block has been fetched, it stays until the cache needs the space. The replacement policy (LRU, FIFO, random) decides which block to evict, and LRU is a direct bet on temporal locality.
Spatial locality
Spatial locality means that if an address is accessed now, addresses close to it are likely to be accessed soon.
Typical sources:
- Sequential instruction fetch, because most instructions are followed by the next one in memory.
- Scanning an array element by element.
- Fields of one struct or object stored next to each other.
- Stack frames, whose variables are adjacent.
The cache exploits spatial locality by fetching a whole block, not a single byte or word. On a miss, the neighbours of the requested address come in with it. If the block is 16 bytes and the elements are 4 bytes, one miss brings in four elements, and the next three accesses can hit.
| Property | Question it answers | Cache mechanism that exploits it |
|---|---|---|
| Temporal locality | Will I use this address again? | Keep the block resident, evict by recency (for example LRU) |
| Spatial locality | Will I use its neighbours? | Fetch a multi-word block on each miss |
A worked example: row-major versus column-major
Languages such as C store a two-dimensional array in row-major order. The element a[i][j] of an N x N array of 4-byte integers sits at address base + (i*N + j) * 4. Consecutive values of j are adjacent in memory.
Take N = 8, so a row is 32 bytes. Assume a 16-byte block, which holds 4 integers. Assume the cache is fully associative with 4 blocks and uses LRU. The base address is 0.
- Row-major traversal (
jis the inner loop) reads addresses 0, 4, 8, 12, 16 and so on. Each block is fetched once, then serves 3 more accesses. There are 256 bytes, so 16 blocks and 16 misses. That leaves 48 hits out of 64. - Column-major traversal (
iis the inner loop) reads addresses 0, 32, 64, ..., 224, then 4, 36, 68, .... Each inner loop touches 8 different blocks, but the cache holds only 4. Under LRU, by the time the loop returns to a block it has been evicted. Every access misses: 0 hits out of 64.
This code reproduces both numbers.
from collections import OrderedDict
def run(addresses, block_size, capacity_blocks):
cache = OrderedDict() # block number -> True, ordered by recency
hits = 0
for a in addresses:
b = a // block_size
if b in cache:
hits += 1
cache.move_to_end(b) # most recently used
else:
if len(cache) == capacity_blocks:
cache.popitem(last=False) # evict least recently used
cache[b] = True
return hits, len(addresses) - hits
N, ELEM = 8, 4
row = [(i * N + j) * ELEM for i in range(N) for j in range(N)]
col = [(i * N + j) * ELEM for j in range(N) for i in range(N)]
print(run(row, 16, 4)) # (48, 16)
print(run(col, 16, 4)) # (0, 64)Both loops do the same arithmetic and touch the same 64 elements. Only the order differs, and the order changes the hit count from 48 to 0.
Temporal locality depends on the working set
Temporal locality only pays off if the data is still in the cache when it is reused. The set of blocks a loop reuses is its working set. If the working set fits in the cache, reuse hits. If it does not, LRU can evict each block just before it is needed again.
The next example reads a 4-element array three times. Blocks hold one element (4 bytes) so that spatial locality plays no part.
from collections import OrderedDict
def run(addresses, block_size, capacity_blocks):
cache = OrderedDict()
hits = 0
for a in addresses:
b = a // block_size
if b in cache:
hits += 1
cache.move_to_end(b)
else:
if len(cache) == capacity_blocks:
cache.popitem(last=False)
cache[b] = True
return hits, len(addresses) - hits
repeat = [k * 4 for _ in range(3) for k in range(4)] # 0,4,8,12 three times
print(run(repeat, 4, 4)) # (8, 4): working set of 4 blocks fits
print(run(repeat, 4, 2)) # (0, 12): cyclic reuse of 4 blocks defeats a 2-block LRU cacheWith 4 blocks of capacity, only the first pass misses, so there are 4 misses and 8 hits. With 2 blocks, the cyclic pattern evicts every block exactly one step before its reuse, so there are no hits at all. The program has the same temporal locality in both runs, but the small cache cannot use it.
Instructions and data
Locality applies to both streams.
- Instruction fetch shows strong spatial locality (straight-line code) and strong temporal locality (loops and frequently called functions). Branches break spatial locality only at jumps.
- Data access varies much more. A sequential array scan has strong spatial locality and no temporal locality, because each element is read once. A scalar accumulator has strong temporal locality and no spatial locality. A linked list or hash table with scattered nodes has weak locality of both kinds.
This is why instruction caches usually have higher hit ratios than data caches.
Block size and locality
Spatial locality is the reason block size matters, but a bigger block is not always better.
- Increasing the block size from very small raises hits, because more neighbours arrive with each miss.
- If the block becomes large, each miss costs more, because more bytes must be transferred, so the miss penalty grows.
- For a fixed cache capacity, larger blocks mean fewer blocks. Fewer blocks can raise conflict misses and cache pollution, where fetched neighbours are never used and push out useful data.
The usual result is that miss ratio falls and then rises as block size grows, with a best value in the middle. GATE questions usually give you the block size, but may ask you to reason about which direction it moves.
Common errors
- Mixing up the two types. A loop counter used on every iteration shows temporal locality. A sequential array scan shows spatial locality. A scan that is repeated many times shows both.
- Calling a single scan temporal. Reading each element of an array once has no temporal locality for the array elements, only spatial.
- Crediting spatial locality when blocks are one word. If the block holds one word, fetching a block brings in no neighbours, so spatial locality gives no benefit.
- Assuming the traversal order does not matter. For a row-major language, the inner loop must run over the last index. In Fortran, which is column-major, it is the opposite.
- Forgetting alignment in counting. When counting misses for a scan of
Sbytes withB-byte blocks, the answer isS / Bonly when the data starts at a block boundary. Otherwise one extra block may be touched. - Assuming locality guarantees hits. Locality is a property of the program. Hits depend on both the program and the cache size, block size and policy.
Quick GATE-style reasoning
When a question gives a loop and asks which locality it shows, work through these steps.
- Find the addresses touched, in order.
- If the same address is touched repeatedly, there is temporal locality.
- If successive addresses are within one block, or adjacent, there is spatial locality.
- For a miss count, divide the elements per block into the elements scanned for sequential access. For strided access, compare the stride with the block size. A stride at or above the block size gives no spatial reuse.
Exercise
A program scans a 1000-element array of 4-byte integers once, from the first element to the last, with a cold cache. The array starts at a block boundary and the block size is 32 bytes. How many misses occur, what is the hit ratio, and which type of locality produces the hits?
Show answer
The array occupies 4000 bytes. With 32-byte blocks that is 4000 / 32 = 125 blocks, and each block is fetched once, so there are 125 misses. The other 1000 - 125 = 875 accesses hit, giving a hit ratio of 875 / 1000 = 0.875. These hits come from spatial locality: each block holds 8 integers, so one miss is followed by 7 hits. There is no temporal locality because each element is read only once.
Exercise
A 16 x 16 array of 4-byte integers is stored in row-major order. The cache has 16-byte blocks and is large enough to hold every block of one row but not the whole array. Which loop order gives fewer misses when summing all elements, and why?
Show answer
Summing with the column index as the inner loop (row by row) is better. It reads consecutive addresses, so each 16-byte block of 4 integers causes 1 miss followed by 3 hits. Summing with the row index as the inner loop jumps 64 bytes between accesses, which is larger than a block, so each access lands in a different block and spatial locality is lost. Because the cache cannot hold the whole array, blocks fetched in one column pass are evicted before the next column reuses them, so most accesses miss.