const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const os = std.os;
const math = std.math;
pub const epoch = @import("time/epoch.zig");
pub fn sleep(nanoseconds: u64) void {
if (std.io.is_async) {
return std.event.Loop.instance.?.sleep(nanoseconds);
}
if (builtin.os.tag == .windows) {
const big_ms_from_ns = nanoseconds / ns_per_ms;
const ms = math.cast(os.windows.DWORD, big_ms_from_ns) orelse math.maxInt(os.windows.DWORD);
os.windows.kernel32.Sleep(ms);
return;
}
if (builtin.os.tag == .wasi) {
const w = std.os.wasi;
const userdata: w.userdata_t = 0x0123_45678;
const clock = w.subscription_clock_t{
.id = w.CLOCK.MONOTONIC,
.timeout = nanoseconds,
.precision = 0,
.flags = 0,
};
const in = w.subscription_t{
.userdata = userdata,
.u = w.subscription_u_t{
.tag = w.EVENTTYPE_CLOCK,
.u = w.subscription_u_u_t{
.clock = clock,
},
},
};
var event: w.event_t = undefined;
var nevents: usize = undefined;
_ = w.poll_oneoff(&in, &event, 1, &nevents);
return;
}
if (builtin.os.tag == .uefi) {
const boot_services = os.uefi.system_table.boot_services.?;
const us_from_ns = nanoseconds / ns_per_us;
const us = math.cast(usize, us_from_ns) orelse math.maxInt(usize);
_ = boot_services.stall(us);
return;
}
const s = nanoseconds / ns_per_s;
const ns = nanoseconds % ns_per_s;
std.os.nanosleep(s, ns);
}
test "sleep" {
sleep(1);
}
pub fn timestamp() i64 {
return @divFloor(milliTimestamp(), ms_per_s);
}
pub fn milliTimestamp() i64 {
return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_ms)));
}
pub fn microTimestamp() i64 {
return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_us)));
}
pub fn nanoTimestamp() i128 {
if (builtin.os.tag == .windows) {
const epoch_adj = epoch.windows * (ns_per_s / 100);
var ft: os.windows.FILETIME = undefined;
os.windows.kernel32.GetSystemTimeAsFileTime(&ft);
const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
return @as(i128, @as(i64, @bitCast(ft64)) + epoch_adj) * 100;
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ns: os.wasi.timestamp_t = undefined;
const err = os.wasi.clock_time_get(os.wasi.CLOCK.REALTIME, 1, &ns);
assert(err == .SUCCESS);
return ns;
}
var ts: os.timespec = undefined;
os.clock_gettime(os.CLOCK.REALTIME, &ts) catch |err| switch (err) {
error.UnsupportedClock, error.Unexpected => return 0,
};
return (@as(i128, ts.tv_sec) * ns_per_s) + ts.tv_nsec;
}
test "timestamp" {
const margin = ns_per_ms * 50;
const time_0 = milliTimestamp();
sleep(ns_per_ms);
const time_1 = milliTimestamp();
const interval = time_1 - time_0;
try testing.expect(interval > 0);
if (!(interval < margin)) return error.SkipZigTest;
}
pub const ns_per_us = 1000;
pub const ns_per_ms = 1000 * ns_per_us;
pub const ns_per_s = 1000 * ns_per_ms;
pub const ns_per_min = 60 * ns_per_s;
pub const ns_per_hour = 60 * ns_per_min;
pub const ns_per_day = 24 * ns_per_hour;
pub const ns_per_week = 7 * ns_per_day;
pub const us_per_ms = 1000;
pub const us_per_s = 1000 * us_per_ms;
pub const us_per_min = 60 * us_per_s;
pub const us_per_hour = 60 * us_per_min;
pub const us_per_day = 24 * us_per_hour;
pub const us_per_week = 7 * us_per_day;
pub const ms_per_s = 1000;
pub const ms_per_min = 60 * ms_per_s;
pub const ms_per_hour = 60 * ms_per_min;
pub const ms_per_day = 24 * ms_per_hour;
pub const ms_per_week = 7 * ms_per_day;
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
pub const Instant = struct {
timestamp: if (is_posix) os.timespec else u64,
const is_posix = switch (builtin.os.tag) {
.wasi => builtin.link_libc,
.windows => false,
else => true,
};
pub fn now() error{Unsupported}!Instant {
if (builtin.os.tag == .windows) {
return Instant{ .timestamp = os.windows.QueryPerformanceCounter() };
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ns: os.wasi.timestamp_t = undefined;
const rc = os.wasi.clock_time_get(os.wasi.CLOCK.MONOTONIC, 1, &ns);
if (rc != .SUCCESS) return error.Unsupported;
return Instant{ .timestamp = ns };
}
const clock_id = switch (builtin.os.tag) {
.macos, .ios, .tvos, .watchos => os.CLOCK.UPTIME_RAW,
.freebsd, .dragonfly => os.CLOCK.MONOTONIC_FAST,
.linux => os.CLOCK.BOOTTIME,
else => os.CLOCK.MONOTONIC,
};
var ts: os.timespec = undefined;
os.clock_gettime(clock_id, &ts) catch return error.Unsupported;
return Instant{ .timestamp = ts };
}
pub fn order(self: Instant, other: Instant) std.math.Order {
if (!is_posix) {
return std.math.order(self.timestamp, other.timestamp);
}
var ord = std.math.order(self.timestamp.tv_sec, other.timestamp.tv_sec);
if (ord == .eq) {
ord = std.math.order(self.timestamp.tv_nsec, other.timestamp.tv_nsec);
}
return ord;
}
pub fn since(self: Instant, earlier: Instant) u64 {
if (builtin.os.tag == .windows) {
const qpc = self.timestamp - earlier.timestamp;
const qpf = os.windows.QueryPerformanceFrequency();
const common_qpf = 10_000_000;
if (qpf == common_qpf) {
return qpc * (ns_per_s / common_qpf);
}
const scale = @as(u64, std.time.ns_per_s << 32) / @as(u32, @intCast(qpf));
const result = (@as(u96, qpc) * scale) >> 32;
return @as(u64, @truncate(result));
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return self.timestamp - earlier.timestamp;
}
const seconds = @as(u64, @intCast(self.timestamp.tv_sec - earlier.timestamp.tv_sec));
const elapsed = (seconds * ns_per_s) + @as(u32, @intCast(self.timestamp.tv_nsec));
return elapsed - @as(u32, @intCast(earlier.timestamp.tv_nsec));
}
};
pub const Timer = struct {
started: Instant,
previous: Instant,
pub const Error = error{TimerUnsupported};
pub fn start() Error!Timer {
const current = Instant.now() catch return error.TimerUnsupported;
return Timer{ .started = current, .previous = current };
}
pub fn read(self: *Timer) u64 {
const current = self.sample();
return current.since(self.started);
}
pub fn reset(self: *Timer) void {
const current = self.sample();
self.started = current;
}
pub fn lap(self: *Timer) u64 {
const current = self.sample();
defer self.started = current;
return current.since(self.started);
}
fn sample(self: *Timer) Instant {
const current = Instant.now() catch unreachable;
if (current.order(self.previous) == .gt) {
self.previous = current;
}
return self.previous;
}
};
test "Timer + Instant" {
const margin = ns_per_ms * 150;
var timer = try Timer.start();
sleep(10 * ns_per_ms);
const time_0 = timer.read();
try testing.expect(time_0 > 0);
if (!(time_0 < margin)) return error.SkipZigTest;
const time_1 = timer.lap();
try testing.expect(time_1 >= time_0);
timer.reset();
try testing.expect(timer.read() < time_1);
}
test {
_ = epoch;
}