Skip to content

Implement clockResolution and CPU-time clocks - #513

Merged
lalinsky merged 4 commits into
mainfrom
clock-resolution
Jun 23, 2026
Merged

lalinsky merged 4 commits into
mainfrom
clock-resolution

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

Implements std.Io's clockResolution properly (it previously hardcoded 1ns) and adds support for the CPU-time clocks, while making our internal clock enum mirror std.Io.Clock.

Clock resolution

  • os.time.resolution now queries the OS: clock_getres on POSIX; derived from QueryPerformanceFrequency (monotonic) and the 100ns RtlGetSystemTimePrecise granularity (realtime) on Windows.
  • clockResolutionImpl reports real granularity instead of a hardcoded 1.

Clock enum mirrors std.Io.Clock

  • Renamed the wall clock field to real (matching std.Io.Clock), keeping realtime and monotonic as decl aliases so existing call sites are unaffected.
  • Added cpu_process and cpu_thread.

awake vs boot now distinct

Previously both collapsed onto CLOCK_MONOTONIC. Now mapped per the std.Io.Clock contract:

clock Linux Darwin other POSIX
awake (exclude suspend) MONOTONIC UPTIME_RAW MONOTONIC
boot (include suspend) BOOTTIME MONOTONIC_RAW MONOTONIC

The BSDs don't expose a distinct include-suspend clock, so both fall back to MONOTONIC (suspend behavior then platform-defined), which std.Io.Clock explicitly permits.

CPU-time clocks

  • POSIX: clock_gettime/clock_getres with PROCESS_CPUTIME_ID / THREAD_CPUTIME_ID. Platforms whose clockid_t lacks these (e.g. SerenityOS) report zero / ClockUnavailable at comptime.
  • Windows: GetProcessTimes / GetThreadTimes summing kernel + user time.
  • now/resolution share one POSIX code path, differing only by clock id.

Testing

  • clockResolution reports a positive granularity for all five clocks.
  • CPU-time clocks are monotonic (no upper-bound vs wall time — Windows accounts CPU in coarse scheduler ticks that can exceed a short QPC window).
  • Verified: full native suite, Windows via wine, aarch64-macos compile.

lalinsky added 2 commits June 23, 2026 18:43
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.
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a9681ce4-d6d3-4ae3-b735-7ddd7c4c3ba0

📥 Commits

Reviewing files that changed from the base of the PR and between fd424d8 and 842e5b4.

📒 Files selected for processing (1)
  • src/io.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/io.zig

📝 Walkthrough

Walkthrough

CPU-time clock support (cpu_process, cpu_thread) is added across the full stack: a reworked Clock enum with aliases and a new resolution() method, Win32 GetProcessTimes/GetThreadTimes bindings, OS-level now()/resolution() implementations for both Windows and POSIX platforms, and IO-layer wiring with updated tests confirming positive granularity and monotonicity.

Changes

CPU-time clock support

Layer / File(s) Summary
Clock enum and Timestamp.now API
src/time.zig
Replaces the two-variant Clock enum with awake, boot, real, cpu_process, cpu_thread variants plus monotonic/realtime aliases. Adds Clock.resolution() delegating to os.time.resolution. Changes Timestamp.now from comptime clock to a runtime parameter.
Win32 CPU-time bindings
src/os/windows.zig
Adds extern "kernel32" declarations for GetProcessTimes and GetThreadTimes, each accepting a handle and four FILETIME output pointers for kernel and user time intervals.
OS-level now() and resolution()
src/os/time.zig
Adds posixClockId() to map logical clocks to clockid_t, routing CPU clocks through platform-specific constants and returning null when unsupported. Updates now() to dispatch CPU-time clocks through windowsCpuTimeNs() on Windows (summing FILETIME kernel+user ticks) and via posixClockId() on POSIX. Introduces the public resolution() function that queries QueryPerformanceFrequency for awake/boot on Windows, returns fixed 100 ns for real and CPU clocks on Windows, and calls clock_getres on POSIX with proper conversion and error handling for unavailable clocks.
IO wiring and tests
src/io.zig
Adds zioClock helper mapping Io.Clock to time.Clock, removing CPU-clock special-cases from nowImpl/clockResolutionImpl that previously returned zero. Replaces the clock-availability test with a positive-granularity assertion for every Io.Clock variant, and adds a monotonicity test for CPU-time clocks by sampling before and after a CPU-busy loop.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • lalinsky/zio#208: Introduced the Timestamp/Clock types and initial os.time APIs that this PR directly extends with new variants and resolution().
  • lalinsky/zio#157: Both PRs update the nowImpl clock-mapping logic in the IO layer to route the .real clock through the underlying system time query instead of prior special-casing.
  • lalinsky/zio#427: Modified the same now(clock: Clock) non-Windows branch in src/os/time.zig that this PR also rewrites around posixClockId.

Poem

⏱️ Two clocks now tick—one for process, one for thread,
No longer sleeping and returning zeros instead.
FILETIME ticks summed up, then queried with care,
posixClockId maps them across each OS layer.
CPU time stops returning zero and actually flows—
Monotonic, resolved, and the stack finally knows. 🎯

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly reflects the main changes: implementing proper clock resolution and adding CPU-time clock support.
Description check ✅ Passed The description comprehensively covers the changes across all files and explains the motivation, implementation details, and testing approach.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch clock-resolution

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Don’t panic when an optional POSIX CPU clock is unavailable at runtime.

posixClockId only handles missing constants. If clock_gettime or clock_getres returns INVAL for .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 win

Let untilNow accept runtime clocks too.

Timestamp.now now accepts a runtime Clock, but untilNow still requires comptime, so callers with a stored clock value can call Timestamp.now(clock) but not ts.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

📥 Commits

Reviewing files that changed from the base of the PR and between 87eb691 and fd4326b.

📒 Files selected for processing (4)
  • src/io.zig
  • src/os/time.zig
  • src/os/windows.zig
  • src/time.zig

Comment thread src/io.zig Resolved
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]>
Repository owner deleted a comment from claude Bot Jun 23, 2026
Repository owner deleted a comment from claude Bot Jun 23, 2026
@lalinsky
lalinsky merged commit 7753471 into main Jun 23, 2026
26 checks passed
@lalinsky
lalinsky deleted the clock-resolution branch June 23, 2026 19:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant