c / expert
Snippet
Cache-Friendly Matrix Processing via Linear Memory Stride Traversal
In C, multi-dimensional arrays are stored in row-major layout in memory. Iterating through columns in the inner loop maximizes L1 cache line hits and CPU prefetching efficiency compared to column-major iteration.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>#define ROWS 4#define COLS 4long sum_matrix_row_major(const int matrix[ROWS][COLS]) {long total = 0;for (int r = 0; r < ROWS; r++) {for (int c = 0; c < COLS; c++) {total += matrix[r][c];}}return total;}int main(void) {int data[ROWS][COLS] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12},{13, 14, 15, 16}};printf("Sum: %ld\n", sum_matrix_row_major(data));return 0;}
Breakdown
1
for (int r = 0; r < ROWS; r++)
Outer loop moves across rows sequentially, maintaining linear memory address progression.
2
total += matrix[r][c];
Accesses adjacent elements sequentially (stride of 1), enabling hardware hardware prefetching.