c / expert
Snippet
Row-Major Vectorizable Dynamic Multidimensional Array Indexing
Linearizing multidimensional array access into a contiguous 1D buffer eliminates pointer-indirection overhead and layout fragmentation. Utilizing the restrict keyword informs the compiler that pointers do not alias, enabling auto-vectorization optimization.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
#include <stddef.h>void compute_tensor_3d(float *restrict data, size_t depth, size_t rows, size_t cols) {for (size_t d = 0; d < depth; ++d) {for (size_t r = 0; r < rows; ++r) {for (size_t c = 0; c < cols; ++c) {size_t index = d * (rows * cols) + r * cols + c;data[index] = data[index] * 2.0f + 1.0f;}}}}
Breakdown
1
void compute_tensor_3d(float *restrict data, size_t depth, size_t rows, size_t cols)
Uses restrict qualifier to guarantee unique memory region access for compiler SIMD vectorization.
2
size_t index = d * (rows * cols) + r * cols + c;
Calculates flattened row-major linear offset for 3D coordinate space access.
3
data[index] = data[index] * 2.0f + 1.0f;
Performs contiguous in-place arithmetic execution optimized for L1 cache line prefetching.