Zig Vectors (SIMD)
Most modern CPUs can add, multiply or compare several numbers with one instruction: four f32s, eight i32s, sometimes more. This is called SIMD (single instruction, multiple data), and it’s one of the main reasons code that crunches numbers (images, audio, physics, statistics) can be fast. Many languages leave SIMD to the optimizer or to special libraries. Zig makes it part of the language with one type: @Vector. You write a + b, and if a and b are vectors, every element gets added at once.
Your first vector
Section titled “Your first vector”@Vector(4, f32) is a type: four f32s that travel together. You create one like an array, and math works element by element:
const std = @import("std");
pub fn main() void { const a: @Vector(4, f32) = .{ 1, 2, 3, 4 }; const b: @Vector(4, f32) = .{ 10, 20, 30, 40 };
const sum = a + b; const product = a * b;
std.debug.print("sum: {any}\n", .{sum}); std.debug.print("product: {any}\n", .{product}); std.debug.print("first: {d}, last: {d}\n", .{ sum[0], sum[3] });}Output:
sum: { 11, 22, 33, 44 }product: { 10, 40, 90, 160 }first: 11, last: 44a + b is one operation on four pairs: 1 + 10, 2 + 20, and so on. You read single elements with [i], just like an array. All the usual operators work element-wise: + - * /, the bitwise ones, @sqrt, @abs, @floor and friends.
Vectors and arrays
Section titled “Vectors and arrays”A vector converts to an array of the same length and type, and back, just by assigning. That’s how you get data in and out:
const std = @import("std");
pub fn main() void { const prices = [4]f32{ 9.99, 4.50, 12.00, 1.25 };
const v: @Vector(4, f32) = prices; const with_tax = v * @as(@Vector(4, f32), .{ 1.2, 1.2, 1.2, 1.2 });
const result: [4]f32 = with_tax; for (result) |p| std.debug.print("{d:.2}\n", .{p});}Output:
11.995.4014.401.50To loop over the values, turn the vector back into an array first, as above. A for loop can’t walk a vector directly:
const std = @import("std");
pub fn main() void { const v: @Vector(3, i32) = .{ 1, 2, 3 }; for (v) |x| std.debug.print("{d}\n", .{x});}main.zig:5:10: error: type '@Vector(3, i32)' does not support field access for (v) |x| std.debug.print("{d}\n", .{x}); ^The message is a bit odd, but the fix is simple: const arr: [3]i32 = v; and loop over arr. Vectors are for doing the same thing to every element at once; arrays are for walking through them.
Mixing in a single number: @splat
Section titled “Mixing in a single number: @splat”Writing .{ 1.2, 1.2, 1.2, 1.2 } to multiply by 1.2 is clumsy. Your first try is probably v * 1.2, but Zig doesn’t let you mix a vector and a single number (a “scalar”):
const std = @import("std");
pub fn main() void { const a: @Vector(4, f32) = .{ 1, 2, 3, 4 }; const twice = a * 2; std.debug.print("{any}\n", .{twice});}main.zig:5:21: error: mixed scalar and vector operands: '@Vector(4, f32)' and 'comptime_int' const twice = a * 2; ~~^~~main.zig:5:19: note: vector here const twice = a * 2; ^@splat(x) makes a vector with x in every slot. Like the cast builtins, it takes its length and type from where the result goes:
const std = @import("std");
pub fn main() void { const celsius: @Vector(4, f32) = .{ -10, 0, 21.5, 100 };
const nine_fifths: @Vector(4, f32) = @splat(9.0 / 5.0); const thirty_two: @Vector(4, f32) = @splat(32); const fahrenheit = celsius * nine_fifths + thirty_two;
std.debug.print("{any}\n", .{fahrenheit});}Output:
{ 14, 32, 70.7, 212 }Four temperatures converted with one multiply and one add. A shorter way to write a splat inline is v * @as(@Vector(4, f32), @splat(2)): the @as gives @splat its result type. Giving the vector type a name helps a lot, as you’ll see below.
Comparisons give a vector of bools
Section titled “Comparisons give a vector of bools”Comparing two vectors compares each pair, and the answer is a vector of bools:
const std = @import("std");
pub fn main() void { const V = @Vector(4, i32); const scores: V = .{ 72, 45, 91, 60 }; const pass_mark: V = @splat(60);
const passed = scores >= pass_mark; std.debug.print("passed: {any}\n", .{passed}); std.debug.print("everyone passed: {}\n", .{@reduce(.And, passed)}); std.debug.print("anyone passed: {}\n", .{@reduce(.Or, passed)});
const zero: V = @splat(0); const kept = @select(i32, passed, scores, zero); std.debug.print("passing scores only: {any}\n", .{kept});}Output:
passed: { true, false, true, true }everyone passed: falseanyone passed: truepassing scores only: { 72, 0, 91, 60 }const V = @Vector(4, i32); names the vector type, which keeps the rest readable. Then:
scores >= pass_markchecks each score on its own.@reduce(.And, passed)squeezes the bools into one:trueonly if every element istrue..Oristrueif any is.@select(i32, mask, a, b)picks fromawhere the mask istrueand frombwhere it’sfalse. It’s aniffor every element at once, without any branching.
Since a comparison gives a vector, not a single bool, you can’t put it straight into an if:
const std = @import("std");
pub fn main() void { const a: @Vector(4, i32) = .{ 1, 2, 3, 4 }; const b: @Vector(4, i32) = .{ 1, 5, 3, 0 }; if (a == b) std.debug.print("same\n", .{});}main.zig:6:11: error: expected type 'bool', found '@Vector(4, bool)' if (a == b) std.debug.print("same\n", .{}); ~~^~~~Decide what you mean: “all equal” is @reduce(.And, a == b), “any equal” is @reduce(.Or, a == b). The and and or keywords don’t work on vectors either, because they skip evaluating the right side, which can’t be done element by element. Use & and | on bool vectors instead.
@reduce: one answer from many
Section titled “@reduce: one answer from many”@reduce turns a vector into a single value. Besides .And and .Or, the common operations are .Add, .Mul, .Min and .Max:
const std = @import("std");
pub fn main() void { const temps: @Vector(5, f32) = .{ 18.5, 21.0, 19.5, 25.0, 16.0 }; const total = @reduce(.Add, temps); std.debug.print("total {d}, average {d}\n", .{ total, total / 5 }); std.debug.print("coldest {d}, warmest {d}\n", .{ @reduce(.Min, temps), @reduce(.Max, temps) });}Output:
total 100, average 20coldest 16, warmest 25The vector length doesn’t have to be a power of two: 5 works fine. Lengths like 4, 8 or 16 just tend to match what the CPU can do in one go.
Processing a long list in chunks
Section titled “Processing a long list in chunks”Real data isn’t four numbers long. The usual pattern is: walk through the slice in chunks of the vector length, keep a running vector, and handle the few leftover items at the end with a normal loop:
const std = @import("std");
fn sum(values: []const f32) f32 { const len = 8; const V = @Vector(len, f32);
var acc: V = @splat(0); var i: usize = 0; while (i + len <= values.len) : (i += len) { const chunk: V = values[i..][0..len].*; acc += chunk; }
var total = @reduce(.Add, acc); while (i < values.len) : (i += 1) total += values[i]; return total;}
pub fn main() void { var data: [20]f32 = undefined; for (&data, 1..) |*d, n| d.* = @floatFromInt(n); std.debug.print("sum of 1 to 20: {d}\n", .{sum(&data)});}Output:
sum of 1 to 20: 210The interesting line is values[i..][0..len].*. values[i..] is the rest of the slice from i; [0..len] with a compile-time len gives a pointer to an array of exactly 8 items; .* copies those 8 into the vector. (It needs the compile-time length: with a plain run-time slice, Zig couldn’t know it fits in 8 slots.) Each round adds 8 numbers with one +=. After the loop, @reduce(.Add, acc) adds up the 8 running totals, and the second while takes care of the last 4 numbers that didn’t fill a chunk.
Is it worth it? On our test machine (a 4-core Linux x86-64 VM, built with -O fast), summing a million f32s took about 0.6 ms with a plain for loop and about 0.15 ms with this 8-wide version. Treat that as one data point: your hardware, data and build will give different numbers, so measure your own code. Part of the gap is that a compiler won’t reorder float additions on its own (it would change the rounding), so it can’t turn the plain loop into SIMD for you. Zig 0.17 also has LLVM’s automatic loop vectorization switched off to avoid a compiler bug (see the 0.17.0 release notes), so explicit vectors matter a bit more in this release.
How wide should my vectors be?
Section titled “How wide should my vectors be?”Any length works, and Zig splits long vectors into several CPU instructions when needed. To match the machine you’re building for, ask the standard library:
const std = @import("std");
pub fn main() void { std.debug.print("f32: {?d} at a time\n", .{std.simd.suggestVectorLength(f32)}); std.debug.print("u8: {?d} at a time\n", .{std.simd.suggestVectorLength(u8)});}On our test machine (an x86-64 Linux VM), you’ll see:
f32: 8 at a timeu8: 32 at a timeOn another CPU you may get 4 and 16, or something else. It returns an optional (null when the target has no SIMD at all), and the value is known at compile time, so you can write const len = std.simd.suggestVectorLength(f32) orelse 4; and use it as a vector length. Keep in mind that the program is then tuned for the CPU it was built for. std.simd has more helpers too, like std.simd.iota (a vector 0, 1, 2, ...) and std.simd.countTrues.
Overflow is still checked
Section titled “Overflow is still checked”Vector math follows the same safety rules as normal math. In a debug or safe build, an integer overflow in any element panics:
const std = @import("std");
pub fn main() void { var bytes: @Vector(4, u8) = .{ 200, 100, 50, 25 }; _ = &bytes; const doubled = bytes + bytes; std.debug.print("{any}\n", .{doubled});}You’ll see something like:
thread 1653 panic: integer overflowmain.zig:6:27: 0x11e3e9a in main (main.zig) const doubled = bytes + bytes; ^If wrapping or capping is what you want (for example, brightening pixels that should stop at 255), use the same operators as for normal integers: +% wraps, and +| saturates (stops at the maximum):
const std = @import("std");
pub fn main() void { const pixels: @Vector(4, u8) = .{ 200, 100, 50, 25 }; const boost: @Vector(4, u8) = @splat(80); std.debug.print("wrap: {any}\n", .{pixels +% boost}); std.debug.print("saturate: {any}\n", .{pixels +| boost});}Output:
wrap: { 24, 180, 130, 105 }saturate: { 255, 180, 130, 105 }For brightness, saturating is clearly right: 200 + 80 should be “as bright as possible”, not a dark 24. The Vectors section of the reference lists all the operations, including @shuffle for rearranging elements, which this page skips.
Practice
Section titled “Practice”1. Distance from a point
Section titled “1. Distance from a point”You have four points’ x and y coordinates in two vectors, xs = .{ 3, 0, 6, 1 } and ys = .{ 4, 5, 8, 1 } (as f32). Compute each point’s distance from (0, 0), which is the square root of x * x + y * y, all at once.
Hint: @sqrt works on a whole vector.
Show solution
const std = @import("std");
pub fn main() void { const V = @Vector(4, f32); const xs: V = .{ 3, 0, 6, 1 }; const ys: V = .{ 4, 5, 8, 1 }; const dist = @sqrt(xs * xs + ys * ys); std.debug.print("{any}\n", .{dist});}Output:
{ 5, 5, 10, 1.4142135 }xs * xs + ys * ys is two multiplies and an add for four points, and @sqrt takes the root of every element. The last one is printed with fewer digits because it’s an f32.
2. Dot product
Section titled “2. Dot product”The dot product of two lists of numbers multiplies them pair by pair and adds up the results. Write dot(a: @Vector(4, f32), b: @Vector(4, f32)) f32 and test it with .{ 1, 2, 3, 4 } and .{ 5, 6, 7, 8 }.
Hint: one * and one @reduce.
Show solution
const std = @import("std");
fn dot(a: @Vector(4, f32), b: @Vector(4, f32)) f32 { return @reduce(.Add, a * b);}
pub fn main() void { std.debug.print("{d}\n", .{dot(.{ 1, 2, 3, 4 }, .{ 5, 6, 7, 8 })});}Output:
701×5 + 2×6 + 3×7 + 4×8 = 70. Dot products are everywhere in graphics and machine learning, and this pair of operations is how SIMD code computes them.
3. Count the hot days
Section titled “3. Count the hot days”Given 8 daily temperatures as a @Vector(8, f32), count how many are above 25 degrees, without a loop.
Hint: compare with a splatted 25 to get a bool vector, then std.simd.countTrues(mask) counts the trues. Or turn the bools into 1s and 0s with @select and @reduce(.Add, ...).
Show solution
const std = @import("std");
pub fn main() void { const V = @Vector(8, f32); const temps: V = .{ 22, 27.5, 31, 19, 25, 26, 18, 30 }; const limit: V = @splat(25); const hot = temps > limit; std.debug.print("hot days: {d}\n", .{std.simd.countTrues(hot)});}Output:
hot days: 4temps > limit gives true for 27.5, 31, 26 and 30. Exactly 25 isn’t “above” 25, so it doesn’t count.
@Vector(n, T)holdsnnumbers (or bools) with a compile-time length, and math on it works element by element, using SIMD instructions where the CPU has them.- Vectors convert to and from arrays by assignment; read one element with
v[i]. - You can’t mix vectors and single numbers: use
@splat(x)to fill a vector. - Comparisons give a vector of bools: combine it with
@reduce(.And / .Or, ...)or use it in@select. @reduce(.Add / .Min / .Max, v)gives one value; on integers,.Addwraps.- For long data, process chunks with
slice[i..][0..len].*and finish the leftovers with a normal loop. - Overflow still panics in safe builds; use
+%or+|when you want wrap or saturate.
Next up: Zig ArrayList, the growable list you’ll use most, and how to manage its memory.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Vectors: the official rules, conversions to arrays and the supported operations.
- Zig language reference: @reduce: turning a vector into one value.
@splatand@select, the other two builtins you’ll use most with vectors, are in the same list of builtins. - Zig 0.17.0 release notes: Loop Vectorization Disabled: why the compiler does less automatic SIMD in 0.17.
- Zig standard library source: simd.zig:
suggestVectorLength,iota,countTruesand other vector helpers, with tests that show how to use them.