#How to do a microbenchmark?

1 messages · Page 1 of 1 (latest)

versed kettle
#

I have this code:

const std = @import("std");
const print = std.debug.print;

pub fn now() u128 {
    return @bitCast(std.time.nanoTimestamp());
}

pub fn fibonacci(n: u64) u64 {
    return if (n <= 1) 0 else (fibonacci(n - 1) + fibonacci(n - 2));
}

pub fn main() void {
    const N = 1000;
    const start = now();
    for (0..N) |_| {
        std.mem.doNotOptimizeAway(fibonacci(25));
    }
    const elapsed = now() - start;
    const avg = @as(f64, @floatFromInt(elapsed)) / @as(f64, @floatFromInt(N));

    print("Average: {d}ns", .{avg});
}

but when I run it with zig build run --release=fast, it shows that the elapsed time is zero... anyone know what's going on here?

sweet nacelle
#

not sure whats going on. when i run w/out the build system:

$ zig run /tmp/tmp.zig
Average: 521766.322ns
$ zig run /tmp/tmp.zig -OReleaseFast
Average: 132.289ns
#

i usually pass -Doptimize=ReleaseFast instead of --release=fast to zig build.

hushed ingot
#

it's probably not the issue here, but your fibonacci function is wrong, returning 0 for all inputs.
the optimiser might be doing something spicy

versed kettle
#

Doesn't seem to have made a difference though

marble flame
#
pub fn now() u128 {
    return @bitCast(std.time.nanoTimestamp());
}

why the bitcast?

#

anyways, i recommend a real profiler like hyperfine

versed kettle
#
pub fn fibonacci(n: u64) u64 {
    if (n <= 1) {
        return 0;
    }
    const a = fibonacci(n - 1);
    std.mem.doNotOptimizeAway(a);
    const b = fibonacci(n - 2);
    std.mem.doNotOptimizeAway(b);
    return a + b;
}

I changed my function to this and it seems to be actually timing it now