CPU caches
published:
This is a great talk by Scott Meyers about why systems developers should care about how CPU caching works. When it comes to CPU performance, cache locality is king.
The SNR in this talk is so high, I need to capture notes to make sure I really get it.
At the end of the day, the hardware determines what is going to happen
One problem he starts with is that of matrix traversals. There are two ways to store matrices in memory: row-major and column-major. So if we want to access every element, there are two possible ways to do this.
Let's consider and example:
///
/// Return a sum of all elements of a matrix
///
long long sum_matrix(const Mat& mat, Traversal_order order) {
long long sum{};
if (order == Traversal_order::row_major) {
for (unsigned r = 0; r < mat.n_rows; ++r) {
for (unsigned c = 0; c < mat.n_cols; ++c) {
sum += mat[r][c];
}
}
} else {
for (unsigned c = 0; c < mat.n_cols; ++c) {
for (unsigned r = 0; r < mat.n_rows; ++r) {
sum += mat[r][c];
}
}
}
return sum;
}
From a pure software perspective, both options are exactly equivalent. You might expect that they should have the same performance profiles...🤔
Another interesting example he provides is that of a function that launches a pool of threads to divide up some work. Say you want to sum only odd values in a given matrix and you have a machine with P cores. You can launch P threads and have each thread work do 1/Pth of the work. That should speed up the computation...🤔...right?
The answer is "maybe"...
Thread memory access matters
Three kinds of caches:
- D-cache D$ ➡️ data cache
- I-cache I$ ➡️ instruction cache
- TLB ➡️ Translation Lookaside Buffer which caches the virtual address translations
Cache lines are key!
Hierarchies of cache:
In Intel Core i7-9xx
- 32KB L1 I$, 32KB L1 D$ per core (shared by two HW threads)
- 256 KB L2 cache per core (Used for data and instructions, shared by two HW threads)
- 8MB L3 cache (holds instructions and data, shared by four cores i.e. eight HW threads)
The difference in access times between L1 cache and main memory is orders of magnitude. I think a couple of GIFs may be a better way to demonstrate the difference.
Here is the L1 cache fetching your instructions or data...
Now here is main memory...
effective memory == CPU cache memory
small == fast as far as the CPU is concerned
- At the CPU level no time/space tradeoff
- Localized code which fits in cache is fastest
- ➡️ this why branching in code is slow, because it makes code non-localized
- compact data structures best (array)
- traversals touching cached data fasted