Compiler optimization for high-performance code

Hi!
I’m currently writing a solver for the wave equation as an exercise in both numerical analysis and writing performant code. I’ve included my code bellow for reference, though what I’m asking is more general.

When compile in debug mode, each simulation step takes ~20ms to run. However, when I compile in ReleaseFast mode, this shrinks to just ~1.5ms. For me, this raises the question of to what extent I should “rely” on the compiler to optimize my code. In other words, should I seek to write the code such that when compiled in debug it is, at the very least, the same order of magnitude as optimized builds or is it sufficient/preferable to write it in such a way that makes it easy for the compiler to optimize, even if debug builds remain slow.

I was hoping that those of you with more experience in games/HPC land could help steer me in the right direction.

Thanks!

Here’s the code:

const std = @import("std");
const math = @import("std").math;
const Io = std.Io;
const rl = @import("raylib");
const print = std.debug.print;
pub const tracy_options = @import("tracy_options");
const tracy = @import("tracy");

const Wavesolver = @import("Wavesolver");

const IVec2 = struct { x: i32, y: i32 };

const Config = struct {
    screen_dims: IVec2 = .{ .x = 800, .y = 600 },
    fps_target: i32 = 60,
};

const Sim_Params = struct {
    width: u32 = 800,
    height: u32 = 600,
    space_step: f32 = 1,
    time_step: f32 = 1,
    base_vel: f32 = 0.5,
    kernel_order: u8 = 3,
};

const Sim_State = struct {
    c0: u8,
    c1: u8,
    c2: u8,
};

pub fn main(init: std.process.Init) !void {
    // Prints to stderr, unbuffered, ignoring potential errors.
    // std.debug.print("All your {s} are belong to us.\n", .{"codebase"});

    // This is appropriate for anything that lives as long as the process.
    const arena: std.mem.Allocator = init.arena.allocator();

    const io = init.io;

    const sim = comptime Sim_Params{};
    const config = Config{ .screen_dims = .{ .x = sim.width, .y = sim.height } };

    rl.setConfigFlags(rl.ConfigFlags{
        .window_resizable = false,
        // .msaa_4x_hint = true,
        // .window_highdpi = true,
    });
    rl.initWindow(config.screen_dims.x, config.screen_dims.y, "raylib");

    var prng = std.Random.DefaultPrng.init(blk: {
        var seed: u64 = undefined;
        io.random(std.mem.asBytes(&seed));
        break :blk seed;
    });

    const rand = prng.random();

    const c_alloc = std.heap.c_allocator;
    var pixels = try c_alloc.alloc(rl.Color, sim.width * sim.height);
    for (pixels, 0..) |_, i| {
        pixels[i] = rl.Color{ .r = 100, .b = 255, .g = 150, .a = 255 };
    }

    // const pixels: [sim.height * sim.width]rl.Color = @splat(rl.Color{ .r = 100, .b = 255, .g = 150, .a = 255 });

    const base_image: rl.Image = .{
        .data = pixels.ptr,
        .width = sim.width,
        .height = sim.height,
        .format = .uncompressed_r8g8b8a8,
        .mipmaps = 1,
    };

    const pixel_texture = try rl.loadTextureFromImage(base_image);
    defer pixel_texture.unload();

    var ss: Sim_State = .{ .c0 = 0, .c1 = 1, .c2 = 2 };

    const u = try arena.create([3][sim.height][sim.width]f32);
    // var u: [3][sim.height][sim.width]f32 = @splat(@splat(@splat(0)));

    const vel = try arena.create([sim.height][sim.width]f32);
    vel.* = @splat(@splat(sim.base_vel));

    const tau = try arena.create([sim.height][sim.width]f32);
    // const kappa = try arena.create([sim.height][sim.width]f32);

    for (0..tau.len) |y| {
        for (0..tau[0].len) |x| {
            tau[y][x] = math.pow(f32, (vel[y][x] * sim.time_step) / sim.space_step, 2);
            // kappa[y][x] = sim.time_step * vel[y][x] / sim.space_step;
        }
    }

    while (!rl.windowShouldClose()) {
        const zone = tracy.Zone.begin(.{
            .name = "full frame",
            .src = @src(),
        });
        defer zone.end();

        // Update

        //Place Drops
        place_rand_drops(u, rand, sim, ss, 0.02);

        // Run simulation step
        sim_step(u, tau, sim, &ss);
        apply_boundary_conditions(u, sim, ss);

        update_display_vals(u, pixels, ss);

        rl.updateTexture(pixel_texture, pixels.ptr);
        // Draw

        rl.beginDrawing();
        defer rl.endDrawing();

        rl.clearBackground(.ray_white);
        rl.drawTexture(pixel_texture, 0, 0, .white);
    }

    // Accessing command line arguments:
    // const args = try init.minimal.args.toSlice(arena);
    // for (args) |arg| {
    //     std.log.info("arg: {s}", .{arg});
    // }

    // In order to do I/O operations need an `Io` instance.

    // Stdout is for the actual output of your application, for example if you
    // are implementing gzip, then only the compressed bytes should be sent to
    // stdout, not any debugging messages.
    // var stdout_buffer: [1024]u8 = undefined;
    // var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
    // const stdout_writer = &stdout_file_writer.interface;
    //
    // try Wavesolver.printAnotherMessage(stdout_writer);

    // try stdout_writer.flush(); // Don't forget to flush!
}

fn place_rand_drops(u: anytype, rand: std.Random, sim: Sim_Params, ss: Sim_State, P_drop: f32) void {
    const zone = tracy.Zone.begin(.{
        .name = "place_rand_drops",
        .src = @src(),
    });
    defer zone.end();
    if (rand.float(f32) < P_drop) {
        const x = rand.intRangeAtMost(u32, 5, sim.width - 5);
        const y = rand.intRangeAtMost(u32, 5, sim.height - 5);
        for (0..3) |c_y| {
            for (0..3) |c_x| {
                u[ss.c0][y + c_y - 2][x + c_x - 2] = 250;
            }
        }
    }
}

fn sim_step(u: anytype, vel: anytype, sim: Sim_Params, ss: *Sim_State) void {
    const zone = tracy.Zone.begin(.{
        .name = "sim_step",
        .src = @src(),
        // .color = .tomato,
    });
    defer zone.end();

    {
        const zone2 = tracy.Zone.begin(.{
            .name = "swap u inidices",
            .src = @src(),
            // .color = .tomato,
        });
        defer zone2.end();

        // u[2] = u[1];
        // u[1] = u[0];
        const ss_tmp = ss.*;
        ss.* = .{ .c0 = ss_tmp.c2, .c1 = ss_tmp.c0, .c2 = ss_tmp.c1 };
        // print("\nCursors: {any}", .{ss});
    }

    {
        const zone2 = tracy.Zone.begin(.{
            .name = "compute laplace kernels",
            .src = @src(),
            // .color = .tomato,
        });
        defer zone2.end();

        if (sim.kernel_order == 2) {
            for (2..(u[0].len - 2)) |y| {
                for (2..(u[0][1].len - 2)) |x| {
                    u[ss.c0][y][x] = vel[y][x] *
                        (-u[ss.c1][y - 2][x] - u[ss.c1][y + 2][x] - u[ss.c1][y][x + 2] - u[ss.c1][y][x - 2] +
                            16 * u[ss.c1][y + 1][x] + 16 * u[ss.c1][y - 1][x] + 16 * u[ss.c1][y][x - 1] + 16 * u[ss.c1][y][x + 1] -
                            60 * u[ss.c1][y][x]) / 12;
                    u[ss.c0][y][x] += 2 * u[ss.c1][y][x] - u[ss.c2][y][x];
                }
            }
        } else if (sim.kernel_order == 1) {
            for (1..(u[0].len - 1)) |y| {
                for (1..(u[0][1].len - 1)) |x| {
                    u[ss.c0][y][x] = vel[y][x] * (u[ss.c1][y - 1][x] + u[ss.c1][y + 1][x] + u[ss.c1][y][x - 1] + u[ss.c1][y][x + 1] - 4 * u[ss.c1][y][x]);
                    u[ss.c0][y][x] += 2 * u[ss.c1][y][x] - u[ss.c2][y][x];
                }
            }
        } else if (sim.kernel_order == 3) {
            for (3..(u[0].len - 3)) |y| {
                for (3..(u[0][1].len - 3)) |x| {
                    u[ss.c0][y][x] = vel[y][x] *
                        (2 * (u[ss.c1][y + 3][x] + u[ss.c1][y - 3][x] + u[ss.c1][y][x - 3] + u[ss.c1][y][x + 3]) +
                            -27 * (u[ss.c1][y + 2][x] + u[ss.c1][y - 2][x] + u[ss.c1][y][x - 2] + u[ss.c1][y][x + 2]) +
                            270 * (u[ss.c1][y + 1][x] + u[ss.c1][y - 1][x] + u[ss.c1][y][x - 1] + u[ss.c1][y][x + 1]) +
                            -980 * u[ss.c1][y][x]) / 180;
                    u[ss.c0][y][x] += 2 * u[ss.c1][y][x] - u[ss.c2][y][x];
                }
            }
        } else if (sim.kernel_order == 4) {
            for (3..(u[0].len - 3)) |y| {
                for (3..(u[0][1].len - 3)) |x| {
                    u[ss.c0][y][x] = vel[y][x] *
                        ((-1 / 560) * (u[ss.c1][y + 4][x] + u[ss.c1][y - 4][x] + u[ss.c1][y][x - 4] + u[ss.c1][y][x + 4]) +
                            (8 / 315) * (u[ss.c1][y + 3][x] + u[ss.c1][y - 3][x] + u[ss.c1][y][x - 3] + u[ss.c1][y][x + 3]) +
                            (-1 / 5) * (u[ss.c1][y + 2][x] + u[ss.c1][y - 2][x] + u[ss.c1][y][x - 2] + u[ss.c1][y][x + 2]) +
                            (8 / 5) * (u[ss.c1][y + 1][x] + u[ss.c1][y - 1][x] + u[ss.c1][y][x - 1] + u[ss.c1][y][x + 1]) +
                            (-205 / 72) * u[ss.c1][y][x]);
                    u[ss.c0][y][x] += 2 * u[ss.c1][y][x] - u[ss.c2][y][x];
                }
            }
        }
    }
}

fn apply_boundary_conditions(u: anytype, sim: Sim_Params, ss: Sim_State) void {
    const zone = tracy.Zone.begin(.{
        .name = "apply_boundary_conditions",
        .src = @src(),
        // .color = .tomato,
    });
    defer zone.end();

    const sz = 10;
    const kappa = sim.base_vel * sim.time_step / sim.space_step;
    const k_term = (kappa - 1) / (kappa + 1);

    for (0..sim.height) |i| {
        for (0..sz) |k| {
            u[ss.c0][i][0 + k] = u[ss.c1][i][1 + k] + k_term * (u[ss.c0][i][1 + k] - u[ss.c1][i][0 + k]);
            u[ss.c0][i][sim.width - 1 - k] = u[ss.c1][i][sim.width - 2 - k] + k_term * (u[ss.c0][i][sim.width - 2 - k] - u[ss.c1][i][sim.width - 1 - k]);
        }
    }

    for (0..sim.width) |j| {
        for (0..sz) |k| {
            u[ss.c0][0 + k][j] = u[ss.c1][1 + k][j] + k_term * (u[ss.c0][1 + k][j] - u[ss.c1][0 + k][j]);
            u[ss.c0][sim.height - 1 - k][j] = u[ss.c1][sim.height - 2 - k][j] + k_term * (u[ss.c0][sim.height - 2 - k][j] - u[ss.c1][sim.height - 1 - k][j]);
        }
    }
}

fn update_display_vals(u: anytype, pixels: anytype, ss: Sim_State) void {
    const zone = tracy.Zone.begin(.{
        .name = "display_sim_val",
        .src = @src(),
        // .color = .tomato,
    });
    defer zone.end();

    // const sim_width = u[ss.c0][0].len;

    const sim_flat: [*]const f32 = @ptrCast(&u[ss.c0]);

    for (0..pixels.len - 1) |i| {
        // const sim_val = @as([u[0].len * u[0][1].len]f32, @bitCast(u[0]))[i];
        // const sim_val = @as([u[0].len * u[0][0].len]f32, @bitCast(u[0]))[i];
        // const sim_val = u[ss.c0][@divFloor(i, sim_width)][i % sim_width];
        const sim_val = sim_flat[i];

        // print("\naccessing coord: [{d}][{d}] = {d}", .{ @divFloor(i, sim_width), i % sim_width, sim_val });
        // if (sim_val < 0) {
        //     print("\n\n\nsim_val negative!: {d}", .{sim_val});
        // }
        const display_val: i16 = @trunc(@min(@max(sim_val, -255), 255));
        pixels[i] = rl.Color{ .r = @intCast(@abs(@min(0, display_val))), .b = @intCast(@max(0, display_val)), .g = 0, .a = 255 };
    }
}

So basically, when someone asks “how can I optimise this”, about 99% of the time that question translates to “how can I add SIMD/multithreading to this”.
My guess is that the majority of the speedup is the compiler “vectorising” your for loops, which is basically turning them into shorter loops which use SIMD registers to do many items in each iteration.
While you could write out this vectorisation explicitly with Zig’s @Vector() type to force the compiler to do this even in debug builds, this ends up obfsucating what your code is actually doing, making it less readable and maintainable.
So I’d say the current state of affairs is fine for you.

From a game dev perspective, there’s utility to being able to hit your target framerate on your dev hardware in debug builds since that lets you iterate on the game without waiting around for release builds.

Assuming that bar is cleared, then it’s a tradeoff. If an easy transformation can get me more headroom in a debug build I might consider it, but I’ll pass if it’s going to be a pain or make the code harder to maintain. There’s nothing wrong with letting the optimizer do it’s job. The performance difference you’re seeing looks pretty typical to me.

I thought loop vectorization was disabled in v17. That’s partially why I was so surprised by the speedup, to your point, I was curious where the speedup came from if not from SIMD (perhaps just much better IPC?) Then again, perhaps I misunderstood which exact optimizations were disabled…

From the 0.17.0 release notes:

Loop Vectorization Disabled to Work Around Regression

In the previous release of Zig, we were forced to disable a key LLVM optimization pass—loop vectorization—to work around a miscompilation which affected the Zig compiler.

Since we first introduced that workaround, a fix has been merged into LLVM’s main branch. However, the fix is not available in LLVM 22, the LLVM version used by Zig 0.17.0. Therefore, this workaround remains enabled for now.

Zig 0.18.0 will upgrade to LLVM 23, so will allow us to re-enable this optimization pass.

That makes total sense for game dev! Thank you!