Skip to content
systemcoding.dev
Performance

Write Your First SSE Intrinsics Loop With _mm_add_ps

Add two float arrays of any length with SSE intrinsics in C: a four-wide main loop, a scalar tail, unaligned loads and the assembly you should see.

6 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the Intel, C and Apple logos.

Adding two arrays element by element is the hello world of SIMD. One loop, one addition per element, and a clear way to make it faster by doing four at a time. This post writes that loop with SSE intrinsics in C on x86-64: a main loop that handles four floats per iteration, a short scalar loop for the leftover elements, and the checks that tell you the compiler produced the instructions you expected. It uses _mm_loadu_ps, _mm_add_ps and _mm_storeu_ps from <xmmintrin.h>, which are part of SSE and available on every x86-64 processor without any compiler flags. We build with GCC 15 or Clang 20. The previous post in this cluster explains vectors and lanes, and the next one ports this loop to AVX2.

The scalar loop first

Start with the plain version, so you have something to compare against:

c
void add_scalar(const float *a, const float *b, float *out, size_t n)
{
    for (size_t i = 0; i < n; ++i)
        out[i] = a[i] + b[i];
}

A compiler at -O3, or at -O2 on GCC 12 and later, may vectorize this on its own. You still write it by hand to learn what the compiler does, and to have a reference for testing.

The SSE loop

Process four elements per iteration while at least four remain, then finish with the scalar loop:

add_sse.cc
#include <stddef.h>
#include <stdio.h>
#include <xmmintrin.h>

void add_sse(const float *a, const float *b, float *out, size_t n)
{
    size_t i = 0;
    for (; i + 4 <= n; i += 4) {
        __m128 va = _mm_loadu_ps(a + i);
        __m128 vb = _mm_loadu_ps(b + i);
        _mm_storeu_ps(out + i, _mm_add_ps(va, vb));
    }
    for (; i < n; ++i)              // tail: 0 to 3 leftover elements
        out[i] = a[i] + b[i];
}

int main(void)
{
    float a[10], b[10], out[10];
    for (int i = 0; i < 10; ++i) {
        a[i] = (float)i;
        b[i] = 100.0f;
    }
    add_sse(a, b, out, 10);
    for (int i = 0; i < 10; ++i)
        printf("%.0f ", out[i]);
    printf("\n");
    return 0;
}
Text
100 101 102 103 104 105 106 107 108 109 

Ten elements make two full iterations of the vector loop, covering indices 0 to 7, and then the tail loop handles indices 8 and 9. The program prints 100 through 109 because each out[i] is i + 100.

Each part of the vector loop has a job. i + 4 <= n is the loop condition written to avoid unsigned overflow: it is equivalent to "at least four elements remain", and it never reads past the end. Writing i < n - 3 would break when n is less than 3, since n - 3 wraps around for an unsigned type. _mm_loadu_ps(a + i) reads 16 bytes starting at a + i into a register, with no alignment requirement. _mm_add_ps(va, vb) adds the four lane pairs. _mm_storeu_ps(out + i, ...) writes four floats back.

Why unaligned loads are fine

The aligned versions _mm_load_ps and _mm_store_ps require 16-byte alignment and fault otherwise. The unaligned versions work on any address, and on current Intel and AMD cores an unaligned load from an address that happens to be aligned runs as fast as an aligned one. An unaligned load that crosses a cache line boundary costs extra, which is the case alignment avoids. For a first loop, use the unaligned forms, and align the buffers later if profiling shows line-crossing loads.

Allocating aligned buffers is easy with C11's aligned_alloc(16, size), where size must be a multiple of 16, or with alignas(16) on a static or automatic array. Do not use the aligned intrinsics on a pointer you did not allocate yourself, since a caller may pass a + 1.

Check the generated code

Compile with gcc -O2 -S -masm=intel add_sse.c and look at add_sse. In the main loop you should see something like:

Text
.L3:
        movups  xmm0, XMMWORD PTR [rdi+rax*4]
        movups  xmm1, XMMWORD PTR [rsi+rax*4]
        addps   xmm0, xmm1
        movups  XMMWORD PTR [rdx+rax*4], xmm0
        add     rax, 4
        cmp     rax, rcx
        jbe     .L3

The exact registers and loop shape vary by compiler version, but the signature is the same: two movups loads, one addps, one movups store, and a counter that advances by four. If you see addss instead, which is a scalar single-precision add, the intrinsics were not used or the loop was not what you thought.

Alias and restrict

The loop assumes that out does not overlap a or b in a way that changes the result. If out == a, the loop is still correct, because each element is read before it is written at the same index. If out == a + 1, the scalar version would propagate values forward, while the vector version reads four elements before writing any of them, so the results differ. When you write the loop with intrinsics, you choose the semantics, and the documentation of your function should say which overlaps are allowed. Adding restrict to the pointers states that no overlap occurs and lets the compiler optimize the scalar tail, and it makes the contract explicit.

c
void add_sse(const float *restrict a, const float *restrict b, float *restrict out, size_t n);

If a caller violates restrict, the behavior is undefined, so use it only when you control the callers or have documented the rule.

Test it against the scalar version

Vector code goes wrong at the boundaries. Test sizes 0, 1, 3, 4, 5, 7, 8 and 9, which exercise every combination of full vectors and tail. Fill the inputs with distinct values so that a swapped index shows up, and compare the output against add_scalar exactly: addition of two floats is the same operation in scalar and vector form, so results are bit-identical, and == is a valid comparison for this loop. That is not true for a sum reduction, where the order of additions changes, as the guide in this cluster explains.

c
for (size_t n = 0; n < 12; ++n) {
    add_scalar(a, b, ref, n);
    add_sse(a, b, out, n);
    if (memcmp(ref, out, n * sizeof(float)) != 0)
        printf("mismatch at n=%zu\n", n);
}

If nothing prints, both versions agree for every length from 0 to 11, which covers each remainder class modulo 4 more than once. Run the test under -fsanitize=address as well: an out-of-bounds read in the vector loop shows up as a heap or stack buffer overflow report.

Performance expectations

Do not expect a speedup of four times. A loop that adds two arrays reads two floats and writes one for each addition, so it is limited by memory bandwidth, not by the adder. For arrays that fit in the cache, the vector version issues a quarter of the instructions and typically runs faster. For arrays far larger than the cache, both versions wait on memory and run at similar speeds. We give no figures because they depend on your machine, and the right way to find out is to time both versions on arrays of the sizes you care about, with a warm-up pass, and report the median of several runs.

The compiler may also already vectorize add_scalar. Check by compiling it alone at -O2 and looking for addps. If it does, your hand-written loop gains nothing, and the main value of the exercise is that you now understand what the compiler produced.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.