zig/lib/std/time.zig

229 lines
8.4 KiB
Zig
Raw Normal View History

2019-05-24 19:52:07 -07:00
const std = @import("std.zig");
const builtin = std.builtin;
2019-05-24 19:52:07 -07:00
const assert = std.debug.assert;
const testing = std.testing;
2019-05-24 19:52:07 -07:00
const os = std.os;
const math = std.math;
2019-05-26 22:35:58 -07:00
pub const epoch = @import("time/epoch.zig");
const is_windows = std.Target.current.os.tag == .windows;
/// Spurious wakeups are possible and no precision of timing is guaranteed.
self-hosted libc detection * libc_installation.cpp is deleted. src-self-hosted/libc_installation.zig is now used for both stage1 and stage2 compilers. * (breaking) move `std.fs.File.access` to `std.fs.Dir.access`. The API now encourages use with an open directory handle. * Add `std.os.faccessat` and related functions. * Deprecate the "C" suffix naming convention for null-terminated parameters. "C" should be used when it is related to libc. However null-terminated parameters often have to do with the native system ABI rather than libc. "Z" suffix is the new convention. For example, `std.os.openC` is deprecated in favor of `std.os.openZ`. * Add `std.mem.dupeZ` for using an allocator to copy memory and add a null terminator. * Remove dead struct field `std.ChildProcess.llnode`. * Introduce `std.event.Batch`. This API allows expressing concurrency without forcing code to be async. It requires no Allocator and does not introduce any failure conditions. However it is not thread-safe. * There is now an ongoing experiment to transition away from `std.event.Group` in favor of `std.event.Batch`. * `std.os.execvpeC` calls `getenvZ` rather than `getenv`. This is slightly more efficient on most systems, and works around a limitation of `getenv` lack of integration with libc. * (breaking) `std.os.AccessError` gains `FileBusy`, `SymLinkLoop`, and `ReadOnlyFileSystem`. Previously these error codes were all reported as `PermissionDenied`. * Add `std.Target.isDragonFlyBSD`. * stage2: access to the windows_sdk functions is done with a manually maintained .zig binding file instead of `@cImport`. * Update src-self-hosted/libc_installation.zig with all the improvements that stage1 has seen to src/libc_installation.cpp until now. In addition, it now takes advantage of Batch so that evented I/O mode takes advantage of concurrency, but it still works in blocking I/O mode, which is how it is used in stage1.
2020-02-16 10:25:30 -08:00
/// TODO integrate with evented I/O
2018-10-10 23:02:59 -07:00
pub fn sleep(nanoseconds: u64) void {
if (is_windows) {
const ns_per_ms = ns_per_s / ms_per_s;
const big_ms_from_ns = nanoseconds / ns_per_ms;
const ms = math.cast(os.windows.DWORD, big_ms_from_ns) catch math.maxInt(os.windows.DWORD);
os.windows.kernel32.Sleep(ms);
return;
}
2019-05-24 19:52:07 -07:00
const s = nanoseconds / ns_per_s;
const ns = nanoseconds % ns_per_s;
std.os.nanosleep(s, ns);
}
/// Get the posix timestamp, UTC, in seconds
2019-05-24 19:52:07 -07:00
/// TODO audit this function. is it possible to return an error?
pub fn timestamp() u64 {
2018-04-18 15:43:35 -07:00
return @divFloor(milliTimestamp(), ms_per_s);
}
2018-04-18 17:57:47 -07:00
/// Get the posix timestamp, UTC, in milliseconds
2019-05-24 19:52:07 -07:00
/// TODO audit this function. is it possible to return an error?
pub fn milliTimestamp() u64 {
if (is_windows) {
2019-05-24 19:52:07 -07:00
//FileTime has a granularity of 100 nanoseconds
// and uses the NTFS/Windows epoch
var ft: os.windows.FILETIME = undefined;
os.windows.kernel32.GetSystemTimeAsFileTime(&ft);
const hns_per_ms = (ns_per_s / 100) / ms_per_s;
const epoch_adj = epoch.windows * ms_per_s;
2019-11-06 20:25:57 -08:00
const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
2019-05-24 19:52:07 -07:00
return @divFloor(ft64, hns_per_ms) - -epoch_adj;
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
2019-05-24 19:52:07 -07:00
var ns: os.wasi.timestamp_t = undefined;
2019-05-24 19:52:07 -07:00
// TODO: Verify that precision is ignored
const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns);
assert(err == os.wasi.ESUCCESS);
2019-05-24 19:52:07 -07:00
const ns_per_ms = 1000;
return @divFloor(ns, ns_per_ms);
}
if (comptime std.Target.current.isDarwin()) {
2019-05-24 19:52:07 -07:00
var tv: os.darwin.timeval = undefined;
var err = os.darwin.gettimeofday(&tv, null);
assert(err == 0);
const sec_ms = tv.tv_sec * ms_per_s;
const usec_ms = @divFloor(tv.tv_usec, us_per_s / ms_per_s);
return @intCast(u64, sec_ms + usec_ms);
}
var ts: os.timespec = undefined;
//From what I can tell there's no reason clock_gettime
// should ever fail for us with CLOCK_REALTIME,
// seccomp aside.
2019-05-24 19:52:07 -07:00
os.clock_gettime(os.CLOCK_REALTIME, &ts) catch unreachable;
const sec_ms = @intCast(u64, ts.tv_sec) * ms_per_s;
const nsec_ms = @divFloor(@intCast(u64, ts.tv_nsec), ns_per_s / ms_per_s);
return sec_ms + nsec_ms;
}
2018-10-10 23:02:59 -07:00
/// Multiples of a base unit (nanoseconds)
pub const nanosecond = 1;
pub const microsecond = 1000 * nanosecond;
pub const millisecond = 1000 * microsecond;
pub const second = 1000 * millisecond;
pub const minute = 60 * second;
pub const hour = 60 * minute;
/// Divisions of a second
pub const ns_per_s = 1000000000;
pub const us_per_s = 1000000;
pub const ms_per_s = 1000;
pub const cs_per_s = 100;
/// Common time divisions
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;
/// A monotonic high-performance timer.
/// Timer.start() must be called to initialize the struct, which captures
/// the counter frequency on windows and darwin, records the resolution,
2018-11-16 10:33:58 -08:00
/// and gives the user an opportunity to check for the existnece of
/// monotonic clocks without forcing them to check for error on each read.
2018-05-28 17:23:55 -07:00
/// .resolution is in nanoseconds on all platforms but .start_time's meaning
/// depends on the OS. On Windows and Darwin it is a hardware counter
/// value that requires calculation to convert to a meaninful unit.
pub const Timer = struct {
2019-05-24 19:52:07 -07:00
///if we used resolution's value when performing the
/// performance counter calc on windows/darwin, it would
/// be less precise
frequency: switch (builtin.os.tag) {
2019-05-24 19:52:07 -07:00
.windows => u64,
2019-05-26 20:35:26 -07:00
.macosx, .ios, .tvos, .watchos => os.darwin.mach_timebase_info_data,
else => void,
},
resolution: u64,
start_time: u64,
2018-05-28 17:23:55 -07:00
2019-05-24 19:52:07 -07:00
const Error = error{TimerUnsupported};
///At some point we may change our minds on RAW, but for now we're
/// sticking with posix standard MONOTONIC. For more information, see:
/// https://github.com/ziglang/zig/pull/933
const monotonic_clock_id = os.CLOCK_MONOTONIC;
/// Initialize the timer structure.
2018-11-16 10:33:58 -08:00
//This gives us an opportunity to grab the counter frequency in windows.
//On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000.
2018-05-28 17:23:55 -07:00
//On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not
// supported, or if the timespec pointer is out of bounds, which should be
2018-11-16 10:33:58 -08:00
// impossible here barring cosmic rays or other such occurrences of
// incredibly bad luck.
//On Darwin: This cannot fail, as far as I am able to tell.
2019-05-24 19:52:07 -07:00
pub fn start() Error!Timer {
var self: Timer = undefined;
2018-05-28 17:23:55 -07:00
if (is_windows) {
2019-05-26 20:35:26 -07:00
self.frequency = os.windows.QueryPerformanceFrequency();
2019-05-24 19:52:07 -07:00
self.resolution = @divFloor(ns_per_s, self.frequency);
2019-05-26 20:35:26 -07:00
self.start_time = os.windows.QueryPerformanceCounter();
} else if (comptime std.Target.current.isDarwin()) {
2019-05-26 20:35:26 -07:00
os.darwin.mach_timebase_info(&self.frequency);
2019-05-24 19:52:07 -07:00
self.resolution = @divFloor(self.frequency.numer, self.frequency.denom);
2019-05-26 20:35:26 -07:00
self.start_time = os.darwin.mach_absolute_time();
2019-05-24 19:52:07 -07:00
} else {
//On Linux, seccomp can do arbitrary things to our ability to call
// syscalls, including return any errno value it wants and
// inconsistently throwing errors. Since we can't account for
// abuses of seccomp in a reasonable way, we'll assume that if
// seccomp is going to block us it will at least do so consistently
var ts: os.timespec = undefined;
os.clock_getres(monotonic_clock_id, &ts) catch return error.TimerUnsupported;
2019-11-06 20:25:57 -08:00
self.resolution = @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
2019-05-24 19:52:07 -07:00
os.clock_gettime(monotonic_clock_id, &ts) catch return error.TimerUnsupported;
2019-11-06 20:25:57 -08:00
self.start_time = @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
}
2019-05-24 19:52:07 -07:00
return self;
}
2018-05-28 17:23:55 -07:00
/// Reads the timer value since start or the last reset in nanoseconds
pub fn read(self: Timer) u64 {
var clock = clockNative() - self.start_time;
return self.nativeDurationToNanos(clock);
}
2018-05-28 17:23:55 -07:00
/// Resets the timer value to 0/now.
pub fn reset(self: *Timer) void {
self.start_time = clockNative();
}
2018-05-28 17:23:55 -07:00
/// Returns the current value of the timer in nanoseconds, then resets it
pub fn lap(self: *Timer) u64 {
var now = clockNative();
var lap_time = self.nativeDurationToNanos(now - self.start_time);
self.start_time = now;
return lap_time;
}
2018-05-28 17:23:55 -07:00
2019-05-24 19:52:07 -07:00
fn clockNative() u64 {
if (is_windows) {
2019-05-26 20:35:26 -07:00
return os.windows.QueryPerformanceCounter();
2019-05-24 19:52:07 -07:00
}
if (comptime std.Target.current.isDarwin()) {
2019-05-26 20:35:26 -07:00
return os.darwin.mach_absolute_time();
2019-05-24 19:52:07 -07:00
}
var ts: os.timespec = undefined;
os.clock_gettime(monotonic_clock_id, &ts) catch unreachable;
2019-11-06 20:25:57 -08:00
return @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
}
fn nativeDurationToNanos(self: Timer, duration: u64) u64 {
if (is_windows) {
return @divFloor(duration * ns_per_s, self.frequency);
}
if (comptime std.Target.current.isDarwin()) {
return @divFloor(duration * self.frequency.numer, self.frequency.denom);
}
return duration;
}
};
2019-05-24 19:52:07 -07:00
test "sleep" {
2018-10-10 23:02:59 -07:00
sleep(1);
}
2019-05-24 19:52:07 -07:00
test "timestamp" {
const ns_per_ms = (ns_per_s / ms_per_s);
const margin = 50;
2018-05-28 17:23:55 -07:00
2018-04-18 15:43:35 -07:00
const time_0 = milliTimestamp();
2018-10-10 23:02:59 -07:00
sleep(ns_per_ms);
2018-04-18 15:43:35 -07:00
const time_1 = milliTimestamp();
const interval = time_1 - time_0;
testing.expect(interval > 0 and interval < margin);
}
2019-05-24 19:52:07 -07:00
test "Timer" {
const ns_per_ms = (ns_per_s / ms_per_s);
2018-05-30 11:38:41 -07:00
const margin = ns_per_ms * 150;
2018-05-28 17:23:55 -07:00
var timer = try Timer.start();
2018-10-10 23:02:59 -07:00
sleep(10 * ns_per_ms);
const time_0 = timer.read();
testing.expect(time_0 > 0 and time_0 < margin);
2018-05-28 17:23:55 -07:00
const time_1 = timer.lap();
testing.expect(time_1 >= time_0);
2018-05-28 17:23:55 -07:00
timer.reset();
testing.expect(timer.read() < time_1);
}