How to write C/C++ loops so that GCC, Clang, and MSVC automatically vectorize them with 256-bit AVX2 instructions:
- Use
#pragma omp simdor#pragma clang loop vectorize(enable). - Avoid loop-carried data dependencies: Each iteration must be independent of prior iterations.
- Use
__restrict__pointers: Informs the compiler that output and input memory buffers never overlap in memory. - Keep trip counts aligned: Iterating in multiples of 8 floats avoids scalar cleanup loop epilogues.
Compiles to native vaddps / vmulps SIMD instructions with an instant 4x to 8x throughput boost!