cpp / expert
Snippet
Hardware-Aligned Structures for Vectorized Processing
Alignment is critical for SIMD (Single Instruction, Multiple Data) performance. Many CPU instructions require data to be aligned to 16, 32, or 64-byte boundaries. Using `alignas` ensures the compiler places the structure at a memory address that is a multiple of the specified value, preventing costly unaligned access penalties.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
struct alignas(16) SIMD_Vector {float channels[4];void load_aligned(const float* data) {// Assume hardware-specific intrinsics herefor(int i = 0; i < 4; ++i) channels[i] = data[i];}};static_assert(sizeof(SIMD_Vector) == 16, "Padding detected!");static_assert(alignof(SIMD_Vector) == 16, "Alignment mismatch!");
Breakdown
1
struct alignas(16) SIMD_Vector
Forces the structure to start on a 16-byte boundary in memory.
2
static_assert(alignof(SIMD_Vector) == 16, ...)
Compile-time verification that the alignment constraint is respected.