mach: introduce cross platform Timer abstraction

This Timer uses std.time.Timer as backing timer in native platforms, and
will use custom timers for special platforms (wasm, android?, ios?).

Unlike std.time.Timer, its primary API is focused on floats. Also meant
to provides some convenient functions alongside base ones.

Follows std.time.Timer API, but methods by default return f32 i.e
non-precise variant with precise variants available returning u64.
This commit is contained in:
iddev5 2022-05-17 13:20:19 +05:30 committed by Stephen Gutekanst
parent be935c64ef
commit 3bb45c75a1
9 changed files with 63 additions and 20 deletions

41
src/Timer.zig Normal file
View file

@ -0,0 +1,41 @@
const std = @import("std");
const builtin = @import("builtin");
const Timer = @This();
backing_timer: BackingTimerType = undefined,
// TODO: verify declarations and its signatures
const BackingTimerType = if (builtin.cpu.arch == .wasm32) void else std.time.Timer;
/// Initialize the timer.
pub fn start() !Timer {
return Timer{
.backing_timer = try BackingTimerType.start(),
};
}
/// Reads the timer value since start or the last reset in nanoseconds.
pub fn readPrecise(timer: *Timer) u64 {
return timer.backing_timer.read();
}
/// Reads the timer value since start or the last reset in seconds.
pub fn read(timer: *Timer) f32 {
return @intToFloat(f32, timer.readPrecise()) / @intToFloat(f32, std.time.ns_per_s);
}
/// Resets the timer value to 0/now.
pub fn reset(timer: *Timer) void {
timer.backing_timer.reset();
}
/// Returns the current value of the timer in nanoseconds, then resets it.
pub fn lapPrecise(timer: *Timer) u64 {
return timer.backing_timer.lap();
}
/// Returns the current value of the timer in seconds, then resets it.
pub fn lap(timer: *Timer) f32 {
return @intToFloat(f32, timer.lapPrecise()) / @intToFloat(f32, std.time.ns_per_s);
}