authorgravatar for leroycepearson@geemili.xyzLeRoyce Pearson <leroycepearson@geemili.xyz> 2020-04-30 20:44:22-06:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-05-24 21:40:08-04:00
logbb4689411563d0f4d0327aefdf36074c54bf7f83
tree2d69eba4a8fd01ba7ef7efb54052b5878d735575
parent4b1a8464715a9b2af1d9024694282883f3346482

Add `std.time.nanoTimestamp` function


1 files changed, 19 insertions(+), 13 deletions(-)

lib/std/time.zig+19-13
......@@ -58,16 +58,25 @@ pub fn timestamp() u64 {
5858/// Get the posix timestamp, UTC, in milliseconds
5959/// TODO audit this function. is it possible to return an error?
6060pub fn milliTimestamp() u64 {
61 return @divFloor(nanoTimestamp(), millisecond);
62}
63
64/// Get the posix timestamp, UTC, in nanoseconds
65///
66/// On windows this only has a granularity of 100 nanoseconds.
67///
68/// TODO audit this function. is it possible to return an error?
69pub fn nanoTimestamp() u64 {
6170 if (is_windows) {
6271 //FileTime has a granularity of 100 nanoseconds
6372 // and uses the NTFS/Windows epoch
6473 var ft: os.windows.FILETIME = undefined;
6574 os.windows.kernel32.GetSystemTimeAsFileTime(&ft);
66 const hns_per_ms = (ns_per_s / 100) / ms_per_s;
67 const epoch_adj = epoch.windows * ms_per_s;
75 const ns_per_hns = 100;
76 const epoch_adj = epoch.windows * ns_per_s;
6877
6978 const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
70 return @divFloor(ft64, hns_per_ms) - -epoch_adj;
79 return (ft64 * hns_per_ms) - -epoch_adj;
7180 }
7281 if (builtin.os.tag == .wasi and !builtin.link_libc) {
7382 var ns: os.wasi.timestamp_t = undefined;
......@@ -76,25 +85,22 @@ pub fn milliTimestamp() u64 {
7685 const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns);
7786 assert(err == os.wasi.ESUCCESS);
7887
79 const ns_per_ms = 1000;
80 return @divFloor(ns, ns_per_ms);
88 return ns;
8189 }
8290 if (comptime std.Target.current.isDarwin()) {
83 var tv: os.darwin.timeval = undefined;
84 var err = os.darwin.gettimeofday(&tv, null);
91 var mts: os.darwin.mach_timespec_t = undefined;
92 var err = os.darwin.clock_get_time(os.darwin.CALENDAR_CLOCK, &mts);
8593 assert(err == 0);
86 const sec_ms = tv.tv_sec * ms_per_s;
87 const usec_ms = @divFloor(tv.tv_usec, us_per_s / ms_per_s);
88 return @intCast(u64, sec_ms + usec_ms);
94 const sec_ns = @as(u64, mts.tv_sec * ns_per_s);
95 return sec_ns + @intCast(u64, mts.tv_nsec);
8996 }
9097 var ts: os.timespec = undefined;
9198 //From what I can tell there's no reason clock_gettime
9299 // should ever fail for us with CLOCK_REALTIME,
93100 // seccomp aside.
94101 os.clock_gettime(os.CLOCK_REALTIME, &ts) catch unreachable;
95 const sec_ms = @intCast(u64, ts.tv_sec) * ms_per_s;
96 const nsec_ms = @divFloor(@intCast(u64, ts.tv_nsec), ns_per_s / ms_per_s);
97 return sec_ms + nsec_ms;
102 const sec_ns = @intCast(u64, ts.tv_sec) * ns_per_s;
103 return sec_ns + @intCast(u64, ts.tv_nsec);
98104}
99105
100106/// Multiples of a base unit (nanoseconds)