Cache hits and cache misses
When the CPU needs data, it first looks in the cache. If found, great -- but what if it is not found?
This lecture helps you understand the core mechanism of how caches work, and the key principle that makes caches effective -- the principle of locality.
A real-life analogy: the desk in a library
You are writing a paper in the library. The desk holds at most 4 books -- this is your 'cache', small in capacity but within arm's reach.
When you need a certain book, first check whether it is on the desk:
- On the desk (cache hit): open and use it directly, zero wait.
- Not on the desk (cache miss): get up, find it on the shelf, bring it back to the desk. If the desk is full, you must put the book you have not opened for the longest time back on the shelf.
This simple rule is exactly the essence of computer cache systems -- 'keep what was used recently, evict what is rarely used'.
Going further, you will find: when writing a paper you do not randomly browse unrelated books. For a certain period of time you repeatedly consult the same batch of references. Of the thousands of shelves of books in the library, the ones you actually touch may be only twenty or thirty. This is the principle of locality at work.
Core concepts: cache hits and misses
Basic terminology
| Term | English | Meaning |
|---|---|---|
| Cache hit | Cache Hit | The data requested by the CPU is found right in the cache and used directly |
| Cache miss | Cache Miss | The data requested by the CPU is not in the cache and must be loaded from the next (slower) level of storage |
| Hit rate | Hit Rate | Hit count / total accesses, the higher the better (ideally close to 100%) |
| Miss penalty | Miss Penalty | The extra time spent loading data from the next level after a miss occurs |
| Hit time | Hit Time | The time needed to read data on a cache hit |
A simple example
Suppose the cache has 3 slots and the CPU accesses addresses [10, 20, 10, 30, 10] in order:
| Step | Address accessed | Cache state (before access) | Result | Reason |
|---|---|---|---|---|
| 1 | 10 | [] | Miss | Cache is empty, address 10 is not in it |
| 2 | 20 | [10] | Miss | Address 20 is not in the cache |
| 3 | 10 | [10, 20] | Hit | Address 10 is in the cache! (temporal locality) |
| 4 | 30 | [10, 20] | Miss | Address 30 is not in the cache |
| 5 | 10 | [10, 20, 30] | Hit | Address 10 hits again |
2 hits out of 5 accesses, hit rate = 40%. Not high, but it already demonstrates the principle of the cache.
Why caches work: the principle of locality
If a program accessed memory purely randomly, a cache would be almost useless -- data loaded in would no longer be needed right away.
But real programs do not behave randomly. They exhibit strong locality, and this is exactly the fundamental reason caches are effective.
Temporal locality
If a piece of data has been accessed, it is likely to be accessed again in the near future.
Typical scenarios:
- Variables in loops:
for i in range(1000000): total += i-- the variableiandtotalis accessed 1 million times in a short period. - Hot code of a function: 20% of a program's code runs 80% of the time; these instructions are frequently revisited.
- Frequently called function parameters: local variables in a recursive function pile up on the stack on each call.
Spatial locality
If a piece of data has been accessed, data near it is also likely to be accessed.
Typical scenarios:
- Continuous traversal of an array:
for i in range(len(arr)): sum += arr[i]-- arr[0], arr[1], arr[2]... they are adjacent in memory. - Fields of a struct/object: after accessing
student.name, it is likely to next accessstudent.age, they are adjacent in memory. - Sequentially executed instructions: after the CPU executes the instruction at address 100, the next one is most likely the instruction at address 104.
Visualization of the two kinds of locality
Temporal locality diagram:
时间轴: t1 t2 t3 t4 t5 t6 t7 t8
访问地址: A B A C A D B A
|_____|_____|_____|
地址 A 在短时间内被多次访问——时间局部性
Spatial locality diagram:
内存地址: 100 104 108 112 116 120 124 128
访问顺序: *1 *2 *3 *4 *5
|_____________________________|
连续访问相邻地址——空间局部性
Modern CPUs exploit spatial locality to boost performance: when loading the data at address 100 from memory, they also load addresses 100~164 (a whole cache line, usually 64 bytes) into the cache together. This way, address 104 is already in the cache when accessed.
Cache replacement policies: what to do when full
Cache slots are limited; when the cache is full and new data must come in, an old piece of data must be evicted. This decision of 'who to evict' is the cache replacement policy.
| Strategy | English | Rule | Evaluation |
|---|---|---|---|
| Least Recently Used | LRU (Least Recently Used) | Evict the data that has not been accessed for the longest time | Most commonly used, works very well |
| First In First Out | FIFO (First In First Out) | Evict the data that entered the cache earliest | Simple but mediocre |
| Least frequently used | LFU (Least Frequently Used) | Evict the data with the fewest accesses | Friendly to hot data, but old data may 'linger' |
| Random replacement | Random | Pick one at random to evict | Simplest to implement, decent results |
LRU performs best in practice because it directly exploits temporal locality -- 'what has not been used recently probably will not be used in the short term'.
Real CPU caches usually use approximate variants of LRU (such as pseudo-LRU) to reduce hardware implementation complexity.
Interactive demo: LRU cache simulator
The Python program below fully simulates how an LRU cache works. You can change the access sequence and cache capacity and observe how the hit rate changes.
Example
"""
LRU cache simulator (runoob demo)
Function:
1. Simulate the CPU's sequence of accesses to memory addresses
2. Manage the cache using the LRU policy
3. Annotate in real time whether each access is a 'hit' or a 'miss'
4. Compute and display the hit rate
"""
from
collections
import
OrderedDict
class
LRUCache:
"""
LRU (Least Recently Used) cache simulator
Use OrderedDict to maintain access order; the closer to the end, the more recently accessed
"""
def
init
(
self
,
capacity
)
:
"""
Initialize the cache
:param capacity: cache capacity (number of entries it can hold)
"""
self
.
capacity
=
capacity
self
.
cache
=
OrderedDict
(
)
Ordered dict: key=address, value=data
self
.
hits
=
0
Hit counter
self
.
misses
=
0
Miss counter
self
.
evictions
=
0
Eviction counter
def
access
(
self
,
address
)
:
"""
Simulate one memory access
:param address: the memory address to access
:return: (result_str, is_hit)
"""
if
address
in
self
.
cache
:
Cache hit!
self
.
hits
=
1
LRU policy: move the hit entry to the end (mark it as recently used)
self
.
cache
.
move_to_end
(
address
)
return
"HIT"
,
True
else
:
Cache miss
self
.
misses
=
1
evicted
=
None
if
len
(
self
.
cache
)
=
self
.
capacity
:
Cache is full, need to evict the least recently used (the first of OrderedDict)
evicted_addr
,
_
=
self
.
cache
.
popitem
(
last
=
False
)
self
.
evictions
=
1
evicted
=
evicted_addr
Load new data from 'next-level storage' (simulated as fetching data directly)
data
=
f
"DATA_AT_{address}"
self
.
cache
[
address
]
=
data
return
"MISS"
,
False
def
hit_rate
(
self
)
:
"""Compute the current cache hit rate (percentage)"""
total
=
self
.
hits
self
.
misses
if
total
==
0
:
return
0.0
return
(
self
.
hits
/ total
)
100
def
current_state
(
self
)
:
"""Return the current cache contents (from oldest to newest)"""
return
list
(
self
.
cache
.
keys
(
)
)
def
run_simulation
(
access_sequence
,
cache_capacity
)
:
"""
Run one complete cache simulation
:param access_sequence: memory access sequence to simulate (list of ints)
:param cache_capacity: cache capacity
"""
cache
=
LRUCache
(
cache_capacity
)
(
"="
70
)
(
f
"RUNOOB LRU cache simulator"
)
(
f
"Cache capacity: {cache_capacity} slots"
)
(
f
"Access sequence: {access_sequence}"
)
(
"="
70
)
(
f
"{'Step':<6} {'Address':<8} {'Result':<8} {'Cache state (old->new)':<40}"
)
(
"-"
70
)
for
i
,
addr
in
enumerate
(
access_sequence
,
1
)
:
result
,
is_hit
=
cache.
access
(
addr
)
state
=
cache.
current_state
(
)
hit_mark
=
"HIT [OK]"
if
is_hit
else
"MISS X"
(
f
"{i:<6} {addr:<8} {hit_mark:<8} {str(state):<40}"
)
Output statistics
(
"-"
70
)
(
f
"\nStatistics:"
)
(
f
" Hit count (Hits) : {cache.hits}"
)
(
f
" Miss count (Misses): {cache.misses}"
)
(
f
" Eviction count (Evictions): {cache.evictions}"
)
(
f
" Hit rate (Hit Rate) : {cache.hit_rate():.1f}%"
)
(
)
return
cache
============================================================
Demo 1: basic LRU behavior
============================================================
(
"\n>>> Demo 1: basic LRU cache behavior"
)
(
"Access sequence shows temporal locality -- address 10 is accessed repeatedly\n"
)
run_simulation
(
access_sequence
=
[
10
,
20
,
10
,
30
,
40
,
10
,
20
,
50
,
10
,
20
]
,
cache_capacity
=
4
)
============================================================
Demo 2: effect of different cache capacities on hit rate
============================================================
(
"\n>>> Demo 2: effect of cache capacity on hit rate"
)
(
"The same access sequence, performance under different cache capacities\n"
)
test_sequence
=
[
1
,
2
,
3
,
4
,
1
,
2
,
5
,
1
,
2
,
3
,
4
,
5
,
1
,
2
,
3
,
4
,
5
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
1
,
2
,
3
,
4
,
5
,
6
,
7
]
(
f
"Access sequence length: {len(test_sequence)}"
)
(
f
{'Capacity':<8} {'Hit':<8} {'Miss':<8} {'Hit rate':<10}"
)
(
"-"
35
)
for
cap
in
[
1
,
2
,
3
,
4
,
5
,
8
,
16
]
:
c
=
LRUCache
(
cap
)
for
addr
in
test_sequence:
c.
access
(
addr
)
(
f
"{cap:<8} {c.hits:<8} {c.misses:<8} {c.hit_rate():<8.1f}%"
)
============================================================
Demo 3: comparing 'locality access' vs 'random access'
============================================================
(
"\n>>> Demo 3: locality access vs random access"
)
(
"The same cache capacity (8), hit rate differences under different access patterns\n"
)
import
random
random
.
seed
(
42
)
Pattern A: access with locality (simulating looping over an array)
local_access
=
[
]
for
_
in
range
(
20
)
:
In each loop, access continuously in the range 0-15, then jump
base
=
random
.
randint
(
0
,
50
)
for
offset
in
range
(
5
)
:
local_access.
append
(
base + offset
)
Pattern B: completely random access
random_access
=
[
random
.
randint
(
0
,
100
)
for
_
in
range
(
100
)
]
for
label
,
seq
in
[
(
"Locality access"
,
local_access
)
,
(
"Random access"
,
random_access
)
]
:
c
=
LRUCache
(
8
)
for
addr
in
seq:
c.
access
(
addr
)
(
f
" {label}: hit rate = {c.hit_rate():.1f}% (total accesses {len(seq)})"
)
Interactive demo: real-time cache hit / miss simulation
Randomly generate a memory access sequence with locality (30 times), animate each cache lookup, compute the hit rate in real time and plot the changing curve
Current address accessed:
--
Ready
Slot 1
null
Slot 2
null
Slot 3
null
Slot 4
null
Hits
0
Misses
0
Hit rate
--
Run this code and you will find:
- The larger the cache capacity, the higher the hit rate -- but the improvement gradually diminishes (marginal effect)
- Access patterns with locality have a much higher hit rate than random access -- this is why caches work
- Under the LRU policy, repeatedly accessed addresses stay in the cache and are almost never evicted
Three types of cache misses
Not all 'cache misses' are the same. Hardware engineers classify them into three types:
| Type | English | When it occurs | Avoidable? |
|---|---|---|---|
| Compulsory miss | Compulsory Miss (Cold Miss) | The first time a piece of data is accessed, it is not yet in the cache | Unavoidable (the first access is always cold) |
| Capacity miss | Capacity Miss | The working set (data actively used by the program) is larger than the cache capacity | Increase the cache or reduce the working set |
| Conflict miss | Conflict Miss | Different addresses are mapped to the same location in the cache (common in direct-mapped caches) | Use set-associative or fully associative mapping |
For ordinary programmers, the first two types come up more often:
- Compulsory miss: unavoidable, but the longer your program runs, the smaller its impact.
- Capacity miss: can be mitigated by optimizing data structure size and access patterns. For example, use more compact data types and process large arrays in blocks.
Understanding cache misses is key to writing high-performance code. A simple rule of thumb: try to make your data access patterns cache-friendly -- traverse arrays in memory layout order, avoid strided access, and keep data that is often used together also close together in memory.
Programming practice: cache-friendly code
Consider a classic example: when traversing a 2D array, row-major vs column-major traversal differs enormously in performance.
Example
"""
Cache-friendly vs cache-unfriendly array traversal (runoob demo)
Demonstrate how different ways of accessing the same data affect cache performance
"""
import
time
How lists are stored in Python: a 2D array = a list of lists
In arr[i][j], arr[i] is a whole row, contiguous in memory
So row-major traversal = cache-friendly, column-major traversal = cache-unfriendly
def
traverse_row_major
(
arr
)
:
"""
Row-major traversal: fix the row index i first, then traverse column j
Access pattern: arr[0][0], arr[0][1], arr[0][2]...
Memory layout: these elements are contiguous in memory -- good spatial locality!
"""
total
=
0
rows
=
len
(
arr
)
cols
=
len
(
arr
[
0
]
)
for
i
in
range
(
rows
)
:
for
j
in
range
(
cols
)
:
total +
=
arr
[
i
]
[
j
]
return
total
def
traverse_column_major
(
arr
)
:
"""
Column-major traversal: fix the column index j first, then traverse row i
Access pattern: arr[0][0], arr[1][0], arr[2][0]...
Memory layout: these elements jump around in memory -- poor spatial locality!
"""
total
=
0
rows
=
len
(
arr
)
cols
=
len
(
arr
[
0
]
)
for
j
in
range
(
cols
)
:
for
i
in
range
(
rows
)
:
total +
=
arr
[
i
]
[
j
]
return
total
Create a large array (1000 x 1000)
SIZE
=
1000
(
f
"Creating a {SIZE}x{SIZE} 2D array..."
)
arr
=
[
[
i * SIZE + j
for
j
in
range
(
SIZE
)
]
for
i
in
range
(
SIZE
)
]
Warm up first to avoid cold-start bias
traverse_row_major
(
arr
)
traverse_column_major
(
arr
)
Formal test
(
"\nStarting performance comparison (run 3 times and average):"
)
(
"-"
50
)
def
benchmark
(
func
,
arr
,
trials
=
3
)
:
"""Average the timing over multiple runs"""
times
=
[
]
for
_
in
range
(
trials
)
:
start
=
time
.
perf_counter
(
)
func
(
arr
)
elapsed
=
time
.
perf_counter
(
)
- start
times.
append
(
elapsed
)
return
sum
(
times
)
/
len
(
times
)
row_time
=
benchmark
(
traverse_row_major
,
arr
)
col_time
=
benchmark
(
traverse_column_major
,
arr
)
(
f
"Row-major traversal (cache-friendly): {row_time:.4f} seconds"
)
(
f
"Column-major traversal (cache-unfriendly): {col_time:.4f} seconds"
)
(
f
"Column is slower than row: {col_time / row_time:.1f} times"
)
(
)
(
"Reason analysis:"
)
(
" In row-major traversal, arr[i][0], arr[i][1], arr[i][2]... are stored contiguously in memory"
)
(
" On the first access to arr[i][0], the CPU loads the following several elements into the cache together"
)
(
" Subsequent accesses to arr[i][1], arr[i][2] then hit the cache directly"
)
(
)
(
" In column-major traversal, arr[0][j], arr[1][j], arr[2][j]... are each separated by a full row in memory"
)
(
" Almost every access needs a load from memory, so the cache hit rate is extremely low"
)
Supplement: a simple test - check memory addresses with Python's id()
(
"\nMemory layout verification (small array demo):"
)
small
=
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
(
f
"id of arr[0][0]: {id(small[0][0])}"
)
(
f
"id of arr[0][1]: {id(small[0][1])} (difference: {id(small[0][1]) - id(small[0][0])})"
)
(
f
"id of arr[0][2]: {id(small[0][2])} (contiguous with [0][0])"
)
(
f
"id of arr[1][0]: {id(small[1][0])} (not contiguous with [0][2] because it crosses a row)"
)