Sub topic 4
Traversal order: row-major access and strides
This chapter assumes you know C arrays and pointers, and that you have read the earlier chapters on cache lines and locality. A cache line is the fixed-size block (commonly 64 bytes) that moves between memory and cache.
How C lays out a 2D array
C stores a two-dimensional array in row-major order. The element m[i][j+1] sits right after m[i][j]. The element m[i+1][j] sits a whole row later.
For a double m[4096][4096], one row is 4096 × 8 = 32768 bytes. Moving one step along j advances 8 bytes. Moving one step along i advances 32768 bytes.
Stride
The stride is the distance in bytes between two consecutive accesses. Stride decides how many useful bytes each cache line delivers.
- Stride 8 bytes (
double, 64-byte line): one line serves 8 accesses. One miss, then seven hits. - Stride 32768 bytes: every access lands in a different line. Almost every access misses, and the other 56 bytes of each loaded line go unused.
The same sum, two orders
#include <stddef.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;
}Both functions do the same arithmetic and return the same value, up to floating-point rounding from the different addition order. The first reads memory in storage order. The second touches a new line on almost every access. The matrix is 128 MiB, far larger than any cache, so a line fetched by the column walk is evicted before the next column needs it. On typical hardware the column version is several times slower, and the gap grows with matrix size.
Rule of thumb
The innermost loop should change the last array index. In C and C++ that is the rightmost subscript. Fortran and MATLAB store arrays column-major, so the rule flips there.
Common errors
- Assuming the compiler fixes it. Compilers can sometimes interchange loops, but you cannot rely on it, especially when pointers might alias or the loop body has side effects.
- Fixing only the loop you noticed. Check every nested loop that touches the same array.
- Judging by small inputs. If the whole matrix fits in cache, the two orders look similar. The difference appears when the data exceeds the cache.
Exercise
A float m[1000][1000] is stored row-major with a 64-byte cache line. A loop sums it with i as the inner loop and j as the outer loop. What is the stride in bytes, and how should you fix the loop?
Show answer
The stride is 1000 × 4 = 4000 bytes, so nearly every access touches a different cache line. Swap the loops so j is the inner loop. The stride becomes 4 bytes, and one cache line serves 16 consecutive floats.