Skip to content
LeetQuant
E11 High-Performance Computing

E11 · High-Performance Computing · Lesson 1 of 4

SIMD

How vector registers process several values per instruction, what stops the compiler auto-vectorising a loop, how to prove it did (remarks and assembly, not hope), and how alignment, data layout and intrinsics fit in, with a measured scalar-versus-vector benchmark.

18 min

One instruction, many lanes

A SIMD (single instruction, multiple data) instruction applies one operation to every lane of a wide register. A 128-bit register holds four 32-bit floats, so one vector add does the work of four scalar adds in roughly the same time. The objective of this lesson: know which loops the compiler can turn into vector code, check that it did, and fix the common reasons it did not.

Instruction setRegister widthfloats per registerdoubles per register
x86 SSE128 bits42
x86 AVX / AVX2256 bits84
x86 AVX-512512 bits168
Arm NEON (AArch64)128 bits42
Arm SVE / SVE2128 to 2048 bits, chosen by the chipvariesvaries

The machine these lessons were measured on reports arm64 from uname -m: an Apple M1, so its vector unit is NEON, 4 floats or 2 doubles per register. Trading servers are usually x86, where AVX2 is the safe baseline and AVX-512 is common on server parts.

What the compiler needs

The loop vectoriser rewrites a loop so that each trip handles WW elements (the vector width) plus a scalar remainder loop. It can only do that when running WW iterations at once gives the same result as running them in order:

  • No loop-carried dependency. a[i] = a[i-1] * 0.5f + b[i] cannot be vectorised: iteration ii needs the result of i−1i-1.
  • No aliasing it cannot rule out. If x and y might overlap, writing y[i] could change a later x[j]. The compiler either inserts a runtime overlap check or gives up; __restrict (a widely supported extension) promises no overlap.
  • Contiguous, predictable access. Unit stride is ideal. Strided access needs shuffles or interleaved loads; indirect access x[idx[i]] needs gather instructions, which are slow or absent.
  • Simple control flow. An if inside the loop can be turned into a computed mask and a blend, but an early break or a call to a function the compiler cannot inline usually blocks vectorisation.
  • Floating-point reductions need permission to reorder. A sum s += x[i] vectorised four ways computes (x0+x4+… )+(x1+x5+… )+…(x_0 + x_4 + \dots) + (x_1 + x_5 + \dots) + \dots, which is a different rounding sequence. IEEE rules forbid the compiler from doing this unless you allow it.

How to check: remarks, then assembly

Never assume a loop was vectorised. Ask the compiler:

  • Clang: -O3 -Rpass=loop-vectorize (vectorised loops), -Rpass-missed=loop-vectorize (loops it rejected) and -Rpass-analysis=loop-vectorize (why).
  • GCC: -O3 -fopt-info-vec-optimized and -fopt-info-vec-missed.
  • Assembly (-S, or Compiler Explorer): on x86, packed instructions end in ps/pd and use xmm/ymm/zmm registers, while scalar ones end in ss/sd. On AArch64, vector instructions carry an arrangement such as .4s (four singles) on v registers; scalar ones use s/d registers.

Clang vectorises at -O2 as well as -O3; GCC has done so at -O2 since version 12, with a more cautious cost model. Then time it, because a remark is not a speed-up, as the benchmark below shows.

A benchmark you can run

Four kernels on 4096 floats (16 KB per array, so everything stays in the L1 cache and the measurement is of the arithmetic, not of memory). saxpy (y←ax+yy \leftarrow a x + y) is compiled once with vectorisation switched off by a pragma and once normally. The sum is written once as a single serial chain and once with eight independent accumulators.

#include <chrono>
#include <cstdio>
#include <vector>

constexpr int N = 4096;     // 16 KB per float array: stays in L1 cache
constexpr int REPS = 50000; // repeat so each kernel runs for a while

void saxpy_scalar(float a, const float* x, float* y, int n) {
#pragma clang loop vectorize(disable) interleave(disable)
  for (int i = 0; i < n; ++i) y[i] = a * x[i] + y[i];
}

void saxpy_auto(float a, const float* __restrict x, float* __restrict y, int n) {
  for (int i = 0; i < n; ++i) y[i] = a * x[i] + y[i];
}

float sum_strict(const float* x, int n) {
  float s = 0.0f;
  for (int i = 0; i < n; ++i) s += x[i];  // one serial dependency chain
  return s;
}

float sum_8acc(const float* x, int n) {  // n divisible by 8
  float s[8] = {};
  for (int i = 0; i < n; i += 8)
    for (int k = 0; k < 8; ++k) s[k] += x[i + k];
  return ((s[0] + s[1]) + (s[2] + s[3])) + ((s[4] + s[5]) + (s[6] + s[7]));
}

template <class F>
double ns_per_element(F f) {  // best of 5 timed runs
  double best = 1e30;
  for (int trial = 0; trial < 5; ++trial) {
    auto t0 = std::chrono::steady_clock::now();
    for (int r = 0; r < REPS; ++r) f();
    auto t1 = std::chrono::steady_clock::now();
    double ns = std::chrono::duration<double, std::nano>(t1 - t0).count();
    if (ns < best) best = ns;
  }
  return best / (double(REPS) * N);
}

int main() {
  std::vector<float> x(N), y(N, 0.0f);
  for (int i = 0; i < N; ++i) x[i] = float(i % 7) * 0.25f;
  volatile float sink = 0.0f;  // stops the compiler deleting the sums

  double t1 = ns_per_element([&] { saxpy_scalar(1e-6f, x.data(), y.data(), N); });
  double t2 = ns_per_element([&] { saxpy_auto(1e-6f, x.data(), y.data(), N); });
  double t3 = ns_per_element([&] { sink = sum_strict(x.data(), N); });
  double t4 = ns_per_element([&] { sink = sum_8acc(x.data(), N); });

  std::printf("saxpy scalar : %.3f ns/elem\n", t1);
  std::printf("saxpy auto   : %.3f ns/elem  (%.1fx)\n", t2, t1 / t2);
  std::printf("sum strict   : %.3f ns/elem\n", t3);
  std::printf("sum 8 accum  : %.3f ns/elem  (%.1fx)\n", t4, t3 / t4);
  std::printf("sums: %.2f %.2f\n", sum_strict(x.data(), N), sum_8acc(x.data(), N));
}

Compiled with c++ -std=c++20 -O3 -Rpass=loop-vectorize -Rpass-missed=loop-vectorize -Rpass-analysis=loop-vectorize, the remarks for the four kernels were (Apple clang 17, AArch64):

:10:3: remark: loop not vectorized: vectorization and interleaving are explicitly disabled, ...
:14:3: remark: vectorized loop (vectorization width: 4, interleaved count: 4)
:19:3: remark: vectorized loop (vectorization width: 4, interleaved count: 4)
:25:3: remark: the cost-model indicates that vectorization is not beneficial

and one run printed:

saxpy scalar : 0.376 ns/elem
saxpy auto   : 0.086 ns/elem  (4.3x)
sum strict   : 1.243 ns/elem
sum 8 accum  : 0.165 ns/elem  (7.5x)
sums: 3071.25 3071.25

These timings are specific to one Apple M1 laptop and vary run to run; over several runs the saxpy speed-up ranged from about 4× to 6× and the accumulator speed-up from about 7× to 10×. Your x86 machine will give different numbers; the shape of the result is what transfers.

Reading the result

  • saxpy, about 4–6×. The vector version uses fmla.4s (fused multiply-add on four lanes), and clang interleaves four such vectors per trip to keep several in flight. Four lanes plus better instruction-level parallelism gives roughly the lane count.
  • Strict sum, slowest. Every add depends on the previous one. At a few cycles of add latency per element, 1.1–1.4 ns per element is that latency chain, not throughput.
  • Eight accumulators, about 8×. Splitting the sum into independent chains gives the hardware both lanes and parallel pipelines to fill: the compiler turns s[0..7] into two .4s vector registers. The result can differ in the last bits from the serial sum in general; here they match because every value is a multiple of 0.25 and every partial sum is exactly representable.

Three ways to let a floating-point reduction vectorise, in order of preference:

  1. Write the independent accumulators yourself (above). Explicit, portable, deterministic for a fixed WW.
  2. #pragma omp simd reduction(+ : s) on that loop, compiled with -fopenmp-simd (no OpenMP runtime needed). This grants reordering for that loop only; on this machine clang then emitted fadd.4s for a plain sum loop.
  3. -ffast-math (or the narrower -fassociative-math). Rebuilt with -ffast-math, sum_strict here dropped to about 0.06 ns per element. But the flag is global: it also lets the compiler assume no NaNs or infinities, which can silently delete an isnan check in risk code.

Alignment

A vector load from an address that is a multiple of the vector width is aligned. On current x86 and Arm cores, unaligned load instructions cost the same as aligned ones unless the access crosses a cache-line (64-byte) boundary; with 512-bit AVX-512 vectors, every misaligned load crosses a line, which is why alignment matters more there.

  • Align buffers with alignas(64), or allocate with std::aligned_alloc or an over-aligned operator new.
  • Tell the compiler with std::assume_aligned<64>(p) (C++20). Lying about it is undefined behaviour.
  • Without that knowledge the compiler may add a peel loop that runs scalar iterations until the pointer is aligned. That is a small fixed cost; it matters for short arrays.

Data layout for SIMD

SIMD wants each lane's operand to sit next to the next lane's operand. Take a 32-byte Order { double px; double qty; long id; int side; int venue; } and a loop computing ∑ipxi×qtyi\sum_i \text{px}_i \times \text{qty}_i:

  • Array of structures (AoS). Consecutive px values are 32 bytes apart. On this machine, with -ffast-math clang vectorised it with ld4.2d, an interleaved load that reads all four 8-byte fields of two records and discards half: half the bytes moved are wasted. On x86 the same pattern often needs shuffles or gathers.
  • Structure of arrays (SoA). px[] and qty[] are separate contiguous arrays: plain vector loads, every byte used.
  • AoSoA (blocks of, say, 8 records stored field-by-field) keeps SIMD-friendly runs while keeping one record's fields close together. It is common in order books and particle codes.

Intrinsics, briefly

When the compiler will not produce the code you need, intrinsics are C functions that map one-to-one to vector instructions. They are not portable, so they are usually wrapped behind #if:

#include <cstdio>
#include <vector>
#if defined(__ARM_NEON)
#include <arm_neon.h>
#elif defined(__AVX2__)
#include <immintrin.h>
#endif

// Sum n floats (n a multiple of 8) with vector accumulators.
float sum_simd(const float* x, int n) {
#if defined(__ARM_NEON)  // 128-bit NEON: 4 floats per register
  float32x4_t a0 = vdupq_n_f32(0.0f), a1 = vdupq_n_f32(0.0f);
  for (int i = 0; i < n; i += 8) {
    a0 = vaddq_f32(a0, vld1q_f32(x + i));
    a1 = vaddq_f32(a1, vld1q_f32(x + i + 4));
  }
  return vaddvq_f32(vaddq_f32(a0, a1));  // horizontal add of 4 lanes
#elif defined(__AVX2__)  // 256-bit AVX: 8 floats per register
  __m256 a = _mm256_setzero_ps();
  for (int i = 0; i < n; i += 8) a = _mm256_add_ps(a, _mm256_loadu_ps(x + i));
  alignas(32) float lanes[8];
  _mm256_store_ps(lanes, a);
  float s = 0.0f;
  for (float v : lanes) s += v;
  return s;
#else
  float s = 0.0f;
  for (int i = 0; i < n; ++i) s += x[i];
  return s;
#endif
}

int main() {
  std::vector<float> x(1024);
  for (int i = 0; i < 1024; ++i) x[i] = 0.5f * float(i % 10);
  std::printf("%.1f\n", sum_simd(x.data(), int(x.size())));
}

Built natively (NEON path) and also for x86-64 with -target x86_64-apple-macos13 -mavx2 (AVX2 path, run under Rosetta), both print 2298.0, which matches the exact sum. The naming pattern is worth recognising: x86 _mm256_add_ps is "256-bit, add, packed single"; NEON vaddq_f32 is "vector add, quad-word (128-bit), float32". For portable code prefer a library such as Highway or xsimd, or std::simd, which was adopted for C++26.

Worked example

will SIMD make this loop 4× faster?

A risk job runs saxpy, yi←axi+yiy_i \leftarrow a x_i + y_i, over 10810^8 floats held in main memory. One core runs the scalar loop at 1 element per cycle at 3 GHz, and can stream about 15 GB/s from DRAM. An engineer proposes rewriting it with AVX2 for an 8× speed-up. What do you expect?

Show solution

Bytes per element. Each element reads xix_i (4 bytes), reads yiy_i (4 bytes) and writes yiy_i (4 bytes): 12 bytes.

Memory-limited rate. 15×109/12=1.25×10915 \times 10^9 / 12 = 1.25 \times 10^9 elements per second, so at least 0.80.8 ns per element, or 8080 ms for 10810^8 elements.

Compute-limited rate, scalar. 1 element per cycle at 3 GHz is 0.330.33 ns per element, or 3333 ms.

The scalar loop is already waiting on memory: 0.8>0.330.8 > 0.33. Making the arithmetic 8× faster takes the compute time to about 4 ms, but the loop still takes about 80 ms. Expect essentially no speed-up. SIMD helps when data is in cache or when there is enough arithmetic per byte (a polynomial, an exponential, a pricing formula per element). For a streaming loop the fixes are fewer bytes: float instead of double, SoA so unused fields are not loaded, or fusing several passes into one so the data is read once.

This is the same contrast as the benchmark above: 16 KB arrays in L1 gave 4–6×, because there the arithmetic was the bottleneck.

Worked example

interview question, 'why didn't this vectorise?'

You are shown this loop and told that clang at -O3 reports it as not vectorised. Name the likely reasons in the order you would check them, and a fix for each.

void scale(float* out, const float* in, const int* idx, int n, float k) {
  for (int i = 0; i < n; ++i) {
    if (in[i] < 0) break;
    out[i] = k * in[idx[i]];
  }
}
Show solution

Talk through the conditions one at a time:

  1. Early exit. The break means the trip count is unknown until run time and iterations after the first negative value must not run. Most loop vectorisers reject loops with data-dependent exits. Fix: find the cut-off first (a separate search loop), then run the main loop to that bound.
  2. Gather. in[idx[i]] is an indirect load. AVX2 and AVX-512 have gather instructions but they are much slower than contiguous loads; NEON has none. Fix: if idx is fixed for many calls, permute the data once into the order it is used.
  3. Aliasing. out might overlap in or idx, so a store could change a later load. Fix: __restrict on the pointers if you can guarantee it, or let the compiler add a runtime overlap check.

Then say how you would confirm: re-run with -Rpass-missed=loop-vectorize -Rpass-analysis=loop-vectorize to see which reason the compiler gives (Apple clang 17 reported "could not determine number of loop iterations", from the break, and "cannot identify array bounds", from the indirect load), and time the result, because a "vectorized" remark alone does not prove a speed-up.

Knowledge check

Why can the compiler not vectorise the loop for (i = 1; i < n; ++i) a[i] = 0.5f * a[i-1] + b[i]; ?

Knowledge check

Clang reports 'vectorized loop (vectorization width: 4)' for a plain float sum compiled without fast-math, yet the loop is no faster than scalar. What is the most likely explanation?

Knowledge check

A loop reads only the price and quantity fields of a million 32-byte order records. Which change most improves its SIMD throughput?

Key takeaways

  • A vector register holds 4 floats (SSE, NEON), 8 (AVX2) or 16 (AVX-512); the best case speed-up is about the lane count, and only when the loop is not memory-bound.
  • Vectorisation needs independent iterations, no possible aliasing, contiguous access, simple control flow, and permission to reorder floating-point reductions.
  • Check with -Rpass=loop-vectorize / -Rpass-missed (clang) or -fopt-info-vec (GCC), then read the assembly and time it: a "vectorized" remark can be an in-order reduction with no speed-up.
  • Prefer structure-of-arrays layouts, independent accumulators and per-loop omp simd over a global -ffast-math.
  • Unaligned loads are cheap except across cache lines; intrinsics are the last resort and need an #if per instruction set.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).