name: benchmark-zig description: Write Zig benchmarks using zBench and std.mem.doNotOptimizeAway. Use when: user wants to benchmark Zig code, measure performance, optimize Zig programs, or compare implementations with statistical analysis. license: MIT
Zig Benchmarking
This skill covers benchmarking Zig code using zBench and manual timing patterns.
Built-in Benchmarking
Zig has built-in benchmarking support via zig test --test-benchmarks.
Writing Benchmarks
Basic Benchmark
const std = @import("std");
fn fibonacci(n: u32) u32 {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "fibonacci benchmark" {
@benchmarkFunction(fibonacci(20));
}
Using zBench (Recommended)
zBench is the standard Zig benchmarking library.
# Add to build.zig
const zbench = @import("zbench");
pub fn build(b: *std.Build) void {
// ...
}
const std = @import("std");
const zbench = @import("zbench");
fn fibonacci(n: u32) u32 {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
pub fn main() void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const results = zbench.bench(allocator, .{
.iterations = 100,
.warm_up_iterations = 10,
}, struct {
fn run() void {
std.mem.doNotOptimizeAway(fibonacci(20));
}
}.run);
std.debug.print("fibonacci(20): {d} ns/op\n", .{results[0].median_ns});
}
Manual Timing
For simpler cases or when you need custom timing:
const std = @import("std");
fn fibonacci(n: u32) u32 {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
pub fn main() void {
const iterations: usize = 10000;
const warmup: usize = 1000;
// Warmup - allow JIT to compile
var i: usize = 0;
while (i < warmup) : (i += 1) {
std.mem.doNotOptimizeAway(fibonacci(20));
}
// Measure
const start = std.time.nanoTimestamp();
i = 0;
while (i < iterations) : (i += 1) {
std.mem.doNotOptimizeAway(fibonacci(20));
}
const end = std.time.nanoTimestamp();
const elapsed = end - start;
const ns_per_op = @as(f64, @floatFromInt(elapsed)) / @as(f64, @floatFromInt(iterations));
std.debug.print("{d} iterations: {d:.2} ns/op\n", .{ iterations, ns_per_op });
}
Preventing Optimizations
std.mem.doNotOptimizeAway
const result = expensiveComputation();
std.mem.doNotOptimizeAway(result); // Prevents DCE
This tells the compiler the value is used and cannot be eliminated.
Runtime Values
// Use runtime-determined value, not constant
const input = getRuntimeValue();
const result = compute(input);
std.mem.doNotOptimizeAway(result);
Running Benchmarks
Using zig test
# Run benchmarks
zig test --test-benchmarks src/bench.zig
# With filter
zig test --test-benchmarks --test-filter "fib" src/bench.zig
Using zBench
zig build-exe bench.zig
./bench
Common Options
| Flag | Description |
|---|---|
--test-benchmarks |
Enable benchmark mode |
-l |
List tests |
--test-filter |
Run matching tests |
Profiling Zig
Tracy Profiler
Tracy is a real-time profiling tool with excellent Zig support.
# Clone and build Tracy
git clone https://github.com/wolfpld/tracy.git
cd tracy/profiler/build
cmake ..
make
const tracy = @import("tracy");
pub fn main() void {
const trace = tracy.trace(@src());
defer trace.end();
// Your code here
doWork();
}
Linux perf
# CPU profile
perf record -g ./my_zig_binary
# Report
perf report
# Flamegraph
perf script | flamegraph.pl > flamegraph.svg
Hardware Counters
perf stat -e cycles,instructions,cache-misses ./my_zig_binary
Memory Profiling
GeneralPurposeAllocator Debug
var gpa = std.heap.GeneralPurposeAllocator(.{
.enable_memory_limit = true,
.verbose_log = true,
}){};
const allocator = gpa.allocator();
// Check for leaks at end
if (gpa.deinit() == .leak) {
@panic("Memory leak detected!");
}
Common Pitfalls
- Always use
doNotOptimizeAway- Prevents DCE and constant folding - Warm up - Run benchmark function several times before measuring
- Release mode - Always benchmark in release mode:
zig build -Drelease-fast - Realistic data - Use runtime values, not constants
- Small operations - Batch multiple operations per iteration for measurable time
Quick Reference
| Task | Command |
|---|---|
| Run benchmarks | zig test --test-benchmarks |
| Build release | zig build -Drelease-fast |
| Run zBench | ./my_bench_binary |
| Tracy profile | Add Tracy, run profiler |
| perf stat | perf stat -e cycles ./binary |
| perf record | perf record -g ./binary |
Timing APIs
// High resolution timer
const start = std.time.nanoTimestamp();
// ... work ...
const end = std.time.nanoTimestamp();
const elapsed = end - start;
// For longer operations
const start_ms = std.time.milliTimestamp();
// Sleeping
std.time.sleep(1_000_000_000); // 1 second in nanoseconds