Skip to content

Conversation

@nlordell
Copy link
Contributor

@nlordell nlordell commented Aug 18, 2025

This PR changes the janet_gettime implementation for OSX <10.12 to read the system clock for (os/clock :monotonic). As far as I was able to find online this is a monotonic clock, although it produces different values from clock_gettime(CLOCK_MONOTONIC, ...) on the same system. I can speculate that this is related to SYSTEM_CLOCK monotonic time being implemented with mach_absolute_time which is documented to not advance during sleep, and I suspect that clock_gettime(CLOCK_MONOTONIC, ...) does.

Resources:

@nlordell
Copy link
Contributor Author

nlordell commented Aug 18, 2025

Disclaimer: I tested the new janet_gettime code on macOS 15 (so not on the system that it was intended for), and it seems to produce decent results.

Normal implementation with clock_gettime:

repl:1:> (os/clock :realtime)
1755506717.49195
repl:2:> (os/clock :monotonic)
65016.336813
repl:3:> (os/clock :cputime)
0.013324

Implementation with the host_get_clock_service-based implementation used by OS X <10.12:

repl:1:> (os/clock :realtime)
1755506806.85266
repl:2:> (os/clock :monotonic)
31583.262315791
repl:3:> (os/clock :cputime)
0.01402

Ideally, this would be tested on an OS X system <10.12 (but I don't have access to one).

This PR changes the `janet_gettime` implementation for OSX <10.12 to
read the system clock for `(os/clock :monotonic)`. As far as I was able
to find online this is _a_ monotonic clock, although it produces
different values from `clock_gettime(CLOCK_MONOTONIC, ...)` on the same
system. I can speculate that this is related to `SYSTEM_CLOCK` monotonic
time being implemented with `mach_absolute_time` which is documented to
_not advance during sleep_, and I suspect that
`clock_gettime(CLOCK_MONOTONIC, ...)` does.

**Resources**:
- `clock_get_time` implementation for the `SYSTEM_CLOCK`:
  <https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/osfmk/kern/clock_oldops.c#L284-L296>
  <https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/arm/rtclock.c#L248-L260>
- `mach_absolute_time` and `mach_continuous_time` definitions:
  <https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/osfmk/mach/mach_time.h#L55-L68>
- Stack overflow post for implementing `clock_gettime` on OS X before 10.12:
  <https://stackoverflow.com/questions/11680461/monotonic-clock-on-osx>
@nlordell nlordell force-pushed the fix/system-monotonic-clock branch from 8a1559b to ad8a5cb Compare August 18, 2025 12:41
@bakpakin bakpakin merged commit 697fdcf into janet-lang:master Aug 18, 2025
13 checks passed
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.

2 participants