Skip to content

Commit b3c729d

Browse files
committed
Use monotonic clock where appropriate
1 parent 2051b38 commit b3c729d

File tree

3 files changed

+17
-12
lines changed

3 files changed

+17
-12
lines changed

libc-bottom-half/clocks/clock.c

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ _Static_assert(
1414

1515
#ifdef __wasilibc_use_wasip2
1616
// Snapshot of the monotonic clock at the start of the program.
17-
static wall_clock_datetime_t start;
17+
static monotonic_clock_instant_t start;
1818

1919
// Use a priority of 10 to run fairly early in the implementation-reserved
2020
// constructor priority range.
2121
__attribute__((constructor(10)))
2222
static void init(void) {
23-
wall_clock_now(&start);
23+
start = monotonic_clock_now();
2424
}
2525

2626
// Define the libc symbol as `__clock` so that we can reliably call it
@@ -30,11 +30,8 @@ clock_t __clock(void) {
3030
// an inherent concept of a process. Note that this means we'll incorrectly
3131
// include time from other processes, so this function is only declared by
3232
// the headers if `_WASI_EMULATED_PROCESS_CLOCKS` is defined.
33-
wall_clock_datetime_t now;
34-
wall_clock_now(&now);
35-
now.seconds -= start.seconds;
36-
now.nanoseconds -= start.nanoseconds;
37-
return (now.seconds + (now.nanoseconds * NSEC_PER_SEC));
33+
monotonic_clock_instant_t now = monotonic_clock_now();
34+
return now - start;
3835
}
3936
#else
4037

libc-bottom-half/cloudlibc/src/libc/time/clock_getres.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,17 @@
1616
int clock_getres(clockid_t clock_id, struct timespec *res) {
1717
#ifdef __wasilibc_use_wasip2
1818
if (res != NULL) {
19-
wall_clock_datetime_t time_result;
20-
wall_clock_resolution(&time_result);
21-
*res = timestamp_to_timespec(&time_result);
19+
if (clock_id == CLOCK_REALTIME) {
20+
wall_clock_datetime_t time_result;
21+
wall_clock_resolution(&time_result);
22+
*res = timestamp_to_timespec(&time_result);
23+
} else if (clock_id == CLOCK_MONOTONIC) {
24+
monotonic_clock_duration_t time_result = monotonic_clock_resolution();
25+
*res = instant_to_timespec(time_result);
26+
} else {
27+
errno = EINVAL; // wasip2 only supports wall and monotonic clocks
28+
return -1;
29+
}
2230
}
2331
#else
2432
__wasi_timestamp_t ts;

libc-bottom-half/cloudlibc/src/libc/time/clock_gettime.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ int __clock_gettime(clockid_t clock_id, struct timespec *tp) {
2626
wall_clock_now(&time_result);
2727
*tp = timestamp_to_timespec(&time_result);
2828
} else {
29-
errno = __WASI_ERRNO_BADF;
30-
return -1;
29+
errno = EINVAL;
30+
return -1; // wasip2 only supports wall and monotonic clocks
3131
}
3232
#else
3333
__wasi_timestamp_t ts;

0 commit comments

Comments
 (0)