Repository navigation
Implement clockResolution and CPU-time clocks - #513
Conversation
Query the OS for actual clock resolution instead of hardcoding 1ns. - os.time.resolution: clock_getres on POSIX, derived from QPC frequency (monotonic) and the 100ns RtlGetSystemTimePrecise granularity (realtime) on Windows. - Clock.resolution method wrapping it. - clockResolutionImpl now reports real granularity for real/awake/boot, still ClockUnavailable for cpu_process/cpu_thread.
Make the clock enum mirror std.Io.Clock: rename the wall clock to `real` (keeping `realtime`/`monotonic` as aliases) and add `cpu_process` and `cpu_thread`. - awake/boot now map to distinct OS clocks where available: MONOTONIC vs BOOTTIME on Linux, UPTIME_RAW vs MONOTONIC_RAW on Darwin, both falling back to MONOTONIC elsewhere (suspend behavior then platform-defined, which std.Io.Clock permits). - CPU-time clocks via clock_gettime(PROCESS/THREAD_CPUTIME_ID) on POSIX and GetProcessTimes/GetThreadTimes on Windows; unsupported platforms report zero (now) and ClockUnavailable (resolution). - now/resolution share one posix code path, differing only by clock id.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughCPU-time clock support ( ChangesCPU-time clock support
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/os/time.zig (1)
82-87: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winDon’t panic when an optional POSIX CPU clock is unavailable at runtime.
posixClockIdonly handles missing constants. Ifclock_gettimeorclock_getresreturnsINVALfor.cpu_process/.cpu_thread, this panics instead of returning zero/null per the clock contract.Proposed runtime fallback
switch (std.posix.errno(rc)) { .SUCCESS => { return .fromTimespec(tp); }, else => |err| { + if ((clock == .cpu_process or clock == .cpu_thread) and err == .INVAL) { + return .zero; + } std.debug.panic("now: call to clock_gettime failed: {}", .{err}); }, } @@ switch (std.posix.errno(rc)) { .SUCCESS => { return Duration.fromNanoseconds(timespecToNanos(tp)); }, else => |err| { + if ((clock == .cpu_process or clock == .cpu_thread) and err == .INVAL) { + return null; + } std.debug.panic("resolution: call to clock_getres failed: {}", .{err}); }, }Also applies to: 121-127
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/os/time.zig` around lines 82 - 87, The error handling in the switch statement checking std.posix.errno(rc) currently panics unconditionally on any non-SUCCESS result. Instead of panicking immediately in the else case, check if the error is INVAL and the clock is one of the optional CPU clocks like .cpu_process or .cpu_thread. For optional clocks returning INVAL at runtime, return zero or null per the clock contract instead of panicking. Only panic if the error is not INVAL or for non-optional clocks. Apply the same fix to the similar clock_getres error handling code that also switches on std.posix.errno(rc) around the same area.
🧹 Nitpick comments (1)
src/time.zig (1)
345-346: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLet
untilNowaccept runtime clocks too.
Timestamp.nownow accepts a runtimeClock, butuntilNowstill requirescomptime, so callers with a stored clock value can callTimestamp.now(clock)but notts.untilNow(clock).Proposed cleanup
- pub fn untilNow(self: Timestamp, comptime clock: Clock) Duration { + pub fn untilNow(self: Timestamp, clock: Clock) Duration { return self.durationTo(now(clock)); }Also applies to: 390-391
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/time.zig` around lines 345 - 346, Update the `untilNow` function to accept a runtime Clock parameter instead of requiring comptime, making it consistent with the `Timestamp.now` function. Change the function signature and implementation of `untilNow` to accept a Clock argument at runtime, allowing callers to use stored clock values with both `Timestamp.now(clock)` and `ts.untilNow(clock)` methods.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/io.zig`:
- Around line 2710-2712: The test loops iterating over the clock types
(including .cpu_process and .cpu_thread) unconditionally use try when calling
Io.Clock.resolution, but this function can return ClockUnavailable when CPU-time
clocks are not supported on the platform. Instead of using try unconditionally,
catch the potential ClockUnavailable error and skip that clock iteration, then
only perform the assertions like checking nanoseconds > 0 and monotonicity
validation for clocks that are actually available. Apply this change to both
test loops mentioned in the comment at lines 2710-2712 and at lines 2724-2732.
---
Outside diff comments:
In `@src/os/time.zig`:
- Around line 82-87: The error handling in the switch statement checking
std.posix.errno(rc) currently panics unconditionally on any non-SUCCESS result.
Instead of panicking immediately in the else case, check if the error is INVAL
and the clock is one of the optional CPU clocks like .cpu_process or
.cpu_thread. For optional clocks returning INVAL at runtime, return zero or null
per the clock contract instead of panicking. Only panic if the error is not
INVAL or for non-optional clocks. Apply the same fix to the similar clock_getres
error handling code that also switches on std.posix.errno(rc) around the same
area.
---
Nitpick comments:
In `@src/time.zig`:
- Around line 345-346: Update the `untilNow` function to accept a runtime Clock
parameter instead of requiring comptime, making it consistent with the
`Timestamp.now` function. Change the function signature and implementation of
`untilNow` to accept a Clock argument at runtime, allowing callers to use stored
clock values with both `Timestamp.now(clock)` and `ts.untilNow(clock)` methods.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 947aa53c-4ec6-4e5c-a874-b1e7364830f6
📒 Files selected for processing (4)
src/io.zigsrc/os/time.zigsrc/os/windows.zigsrc/time.zig
Some platforms include PROCESS_CPUTIME_ID/THREAD_CPUTIME_ID in clockid_t but don't support them at runtime, returning EINVAL. Return zero/null instead of panicking, and skip those clocks in tests via ClockUnavailable. Co-authored-by: Lukáš Lalinský <[email protected]>
The previous fix used `continue` inside a catch block within an `inline for`, which is invalid in Zig: `inline for` uses comptime continue/break, but a catch block is a runtime context. Switch to a regular `for` loop, which is valid since Io.Timestamp.now accepts a runtime Io.Clock. Co-authored-by: Lukáš Lalinský <[email protected]>
Summary
Implements
std.Io'sclockResolutionproperly (it previously hardcoded 1ns) and adds support for the CPU-time clocks, while making our internal clock enum mirrorstd.Io.Clock.Clock resolution
os.time.resolutionnow queries the OS:clock_getreson POSIX; derived fromQueryPerformanceFrequency(monotonic) and the 100nsRtlGetSystemTimePrecisegranularity (realtime) on Windows.clockResolutionImplreports real granularity instead of a hardcoded1.Clock enum mirrors
std.Io.Clockreal(matchingstd.Io.Clock), keepingrealtimeandmonotonicas decl aliases so existing call sites are unaffected.cpu_processandcpu_thread.awake vs boot now distinct
Previously both collapsed onto
CLOCK_MONOTONIC. Now mapped per thestd.Io.Clockcontract:awake(exclude suspend)MONOTONICUPTIME_RAWMONOTONICboot(include suspend)BOOTTIMEMONOTONIC_RAWMONOTONICThe BSDs don't expose a distinct include-suspend clock, so both fall back to
MONOTONIC(suspend behavior then platform-defined), whichstd.Io.Clockexplicitly permits.CPU-time clocks
clock_gettime/clock_getreswithPROCESS_CPUTIME_ID/THREAD_CPUTIME_ID. Platforms whoseclockid_tlacks these (e.g. SerenityOS) report zero /ClockUnavailableat comptime.GetProcessTimes/GetThreadTimessumming kernel + user time.now/resolutionshare one POSIX code path, differing only by clock id.Testing
clockResolutionreports a positive granularity for all five clocks.