Sub topic 4
Traversal Order: Row-Major Access and Strides
What this chapter assumes
You should know C or a similar language, how multidimensional arrays are declared, and what a pointer is. You should also know the previous chapters' model: data moves between memory levels in cache lines, commonly 64 bytes. This chapter applies that model to the simplest case, a loop over a 2D array.
Row-major layout
Memory is a single line of byte addresses. A 2D array has to be flattened into that line. C, C++, Rust and NumPy's default order flatten it row-major: all of row 0, then all of row 1, and so on. For a double m[N][N], element m[i][j] lives at:
address = base + (i * N + j) * sizeof(double)Elements that differ only in j are neighbors. Elements that differ only in i are N * sizeof(double) bytes apart.
Fortran, MATLAB and R use column-major layout, which swaps the rule. The fast index there is the first one. A loop order that is good in C is bad in Fortran, so check the layout of the language and library you are using before choosing a loop order.
Stride
The stride of a loop is the distance in bytes between the addresses it touches on consecutive iterations. Stride decides how much of each cache line you use before moving on.
| Stride (bytes) | `double`s per 64-byte line used | Misses per access, cold cache |
|---|---|---|
| 8 | 8 | 1/8 |
| 16 | 4 | 1/4 |
| 32 | 2 | 1/2 |
| 64 or more | 1 | 1 |
Once the stride reaches the line size, every access lands in a new line. The other 56 bytes of each fetched line are wasted bandwidth.
The two traversals
Both functions below compute the same sum. Only the loop nesting differs.
#define _POSIX_C_SOURCE 199309L
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4096
/* Walks memory sequentially: m[i][j] and m[i][j+1] are adjacent. */
double sum_row_major(const double (*m)[N]) {
double s = 0.0;
for (size_t i = 0; i < N; i++)
for (size_t j = 0; j < N; j++)
s += m[i][j];
return s;
}
/* Jumps N * sizeof(double) bytes between accesses. */
double sum_col_major(const double (*m)[N]) {
double s = 0.0;
for (size_t j = 0; j < N; j++)
for (size_t i = 0; i < N; i++)
s += m[i][j];
return s;
}
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (double)t.tv_sec + (double)t.tv_nsec * 1e-9;
}
int main(void) {
double (*m)[N] = malloc(sizeof(double[N][N]));
if (!m) return 1;
for (size_t i = 0; i < N; i++)
for (size_t j = 0; j < N; j++)
m[i][j] = 1.0;
double t0 = now();
double a = sum_row_major(m);
double t1 = now();
double b = sum_col_major(m);
double t2 = now();
printf("row-major: %.0f in %.3f s\n", a, t1 - t0);
printf("col-major: %.0f in %.3f s\n", b, t2 - t1);
free(m);
return 0;
}Build with cc -O2 -o traverse traverse.c. Printing the sums keeps the compiler from deleting the loops. The matrix is 128 MiB, far larger than any cache. On typical desktop hardware the column-order loop is several times slower. The exact ratio depends on the machine.
Why the gap can exceed 8x
The simple model says column order uses 1 of 8 doubles per line, so it should cost about 8 times more memory traffic. Three further effects can make it worse.
- Reuse is lost. One column pass touches 4096 different lines, about 256 KiB. The next column,
j + 1, needs the same lines. That reuse only works if all 4096 lines survive in cache until then. They do not fit in a typical 32 to 48 KiB L1 data cache. - Power-of-two strides cause conflicts. Here the stride is 32768 bytes. A typical L1 has 64 sets of 64-byte lines, and the set is chosen from address bits 6 to 11. A stride of 32768 never changes those bits, so every access in a column maps to the same set. That set holds only its associativity worth of lines, often 8, so the others are evicted before reuse. A later chapter covers this in detail.
- Every access may touch a new page. A 4096-byte page is smaller than the stride. Each access can need a different address translation, which stresses the TLB (translation lookaside buffer). A later chapter covers this too.
Hardware prefetchers can detect constant strides, but they usually stop at page boundaries. A stride of 32768 bytes crosses a page on every access, so prefetching gives little help here.
Common errors
- Choosing the loop order from the math, not the layout. Writing
for joutsidefor ibecause the formula is indexed that way is the usual cause of this bug. Put the loop over the last index innermost in C. - Trusting the compiler to fix it. Some compilers can swap loops (loop interchange). For this sum, swapping reorders floating-point additions, which can change the result. Without flags such as
-ffast-math, a compiler generally must not do it. Treat interchange as a bonus, never as a plan. - Benchmarking a loop whose result is unused. The compiler may remove it. Use the result, as the example does.
- Timing the first pass only. The first pass pays page faults and cold misses. Repeat the measurement and report the minimum or median.
- Ignoring the hidden column walk. In matrix multiplication
C[i][j] += A[i][k] * B[k][j], the innermostkloop walks down a column ofB. Reordering toi, k, jmakes all three accesses sequential in the inner loop.
Checking your work
Read the loop and name the stride of the innermost index. If it is sizeof(element), you are sequential. If it is a row length, you are strided. Then confirm with a measurement, since the model predicts the direction of the change but not its size.
Exercise
In double a[1000][1000] with 64-byte cache lines, what is the byte stride and the number of useful doubles per fetched line when the inner loop runs over the first index? What is the fix?
Show answer
The stride is 1000 * 8 = 8000 bytes, which is larger than a line, so each access fetches a new line and uses 1 of its 8 doubles. Swap the loops so the inner loop runs over the second index, which gives stride 8 and 8 useful doubles per line.
Exercise
A loop reads m[i][j] for rows of 2048 floats, with the inner loop over i. Why might its speed collapse at this width in particular, beyond the 1-in-16 line use?
Show answer
The stride is 2048 * 4 = 8192 bytes, a power of two. Addresses with that stride map to a small number of cache sets, so lines evict each other (conflict misses) before the next column reuses them. Padding each row by one cache line, or changing the loop order, avoids it.