Miiao
Miiao

Reputation: 998

Make the compiler not optimize _ out

I'm writing a benchmark of a simple function.

var timer = try std.time.Timer.start();
_ = f();
const elapsed = timer.read();

Unfortunately, the value marked with placeholder syntax gets optimized out, so elapsed equals zero. To fix this, i'm using a terrible hack:

comptime {
    asm (
        \\.global dummy;
        \\dummy:
        \\ret
    );
}
extern fn dummy(x: i32) void;

// ...
var timer = try std.time.Timer.start();
dummy(f());
const elapsed = timer.read();
/// ...

And it works as expected. I, however, am surely not happy with such a solution. Similar code in Rust would just use black_box intrinsic, in Nim would use used pragma and in C it could be solved using volatile while declaring the result variable.

Is there a better solution in Zig?

Upvotes: 1

Views: 613

Answers (1)

sigod
sigod

Reputation: 6397

Use std.mem.doNotOptimizeAway:

std.mem.doNotOptimizeAway(f());

In the future, it will be replaced by @declareSideEffect builtin function:

_ = @declareSideEffect(f());

Upvotes: 2

Related Questions