Skip to content
v1.0.0-zig0.15.2

Cookbook Overview

Practical recipes showing how to solve real-world problems with Blitz. Each recipe follows the same structure: a problem statement, a complete solution with working Zig code, an explanation of which APIs are used and why, and performance guidance.

RecipeDescriptionKey APIs
Image ProcessingPixel transforms, grayscale conversion, and gaussian blur on image buffersparallelFor, iterMut().mapInPlace()
CSV Data ParsingParse CSV lines in parallel and aggregate numeric resultsparallelReduce, join()
Monte Carlo SimulationEstimate pi using random sampling across threadsparallelReduce, range()
Log File AnalysisSearch logs for patterns, count errors, and find specific entriesiter().any(), iter().findAny(), join()
Matrix MultiplicationDense matrix multiply with parallel row computationparallelFor with context

These recipes demonstrate different Blitz APIs. Use this guide to pick the right one for your task:

Task PatternRecommended APIWhy
Transform every elementiterMut().mapInPlace()In-place, zero allocation
Aggregate to single valueiter().sum() / .min() / .max()Optimized parallel reduction
Custom aggregationiter().reduce() or parallelReduce()Full control over combine logic
Search for elementiter().findAny() / .any() / .all()Early exit stops all workers
Index-based loop with contextparallelFor()Access external data via context struct
Multiple independent tasksjoin()Named results, heterogeneous types
Range-based computationrange().forEach() / .sum()No backing slice needed

Most low-level APIs use a context struct to pass data into the parallel body:

const Context = struct {
input: []const f64,
output: []f64,
scale: f64,
};
blitz.parallelFor(n, Context, .{
.input = input,
.output = output,
.scale = 2.0,
}, struct {
fn body(ctx: Context, start: usize, end: usize) void {
for (ctx.input[start..end], ctx.output[start..end]) |in, *out| {
out.* = in * ctx.scale;
}
}
}.body);

For small data sizes, the overhead of parallelism exceeds the benefit. Blitz handles this internally for iterator operations, but for custom algorithms you should add your own thresholds:

if (data.len < 10_000) {
// Sequential fallback
for (data) |*v| v.* = transform(v.*);
} else {
blitz.iterMut(f64, data).mapInPlace(transform);
}

When using parallelReduce or iter().reduce(), the combine function must be associative. Addition, multiplication, min, and max all qualify. Subtraction and division do not.