Skip to content

Commit ce480e8

Browse files
nslowellnashif
authored andcommitted
posix: clock: nanosecond resolution
directly convert ticks to nsecs in the clock_* posix functions which will provide the best resolution the system allows Signed-off-by: Nicholas Lowell <[email protected]>
1 parent a42d6c9 commit ce480e8

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

lib/posix/clock.c

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ static struct timespec rt_clock_base;
2525
*/
2626
int z_impl_clock_gettime(clockid_t clock_id, struct timespec *ts)
2727
{
28-
uint64_t elapsed_msecs;
28+
uint64_t elapsed_nsecs;
2929
struct timespec base;
3030

3131
switch (clock_id) {
@@ -43,10 +43,9 @@ int z_impl_clock_gettime(clockid_t clock_id, struct timespec *ts)
4343
return -1;
4444
}
4545

46-
elapsed_msecs = k_uptime_get();
47-
ts->tv_sec = (int32_t) (elapsed_msecs / MSEC_PER_SEC);
48-
ts->tv_nsec = (int32_t) ((elapsed_msecs % MSEC_PER_SEC) *
49-
USEC_PER_MSEC * NSEC_PER_USEC);
46+
elapsed_nsecs = k_ticks_to_ns_floor64(k_uptime_ticks());
47+
ts->tv_sec = (int32_t) (elapsed_nsecs / NSEC_PER_SEC);
48+
ts->tv_nsec = (int32_t) (elapsed_nsecs % NSEC_PER_SEC);
5049

5150
ts->tv_sec += base.tv_sec;
5251
ts->tv_nsec += base.tv_nsec;
@@ -84,9 +83,9 @@ int clock_settime(clockid_t clock_id, const struct timespec *tp)
8483
return -1;
8584
}
8685

87-
uint64_t elapsed_msecs = k_uptime_get();
86+
uint64_t elapsed_nsecs = k_ticks_to_ns_floor64(k_uptime_ticks());
8887
int64_t delta = (int64_t)NSEC_PER_SEC * tp->tv_sec + tp->tv_nsec
89-
- elapsed_msecs * USEC_PER_MSEC * NSEC_PER_USEC;
88+
- elapsed_nsecs;
9089

9190
base.tv_sec = delta / NSEC_PER_SEC;
9291
base.tv_nsec = delta % NSEC_PER_SEC;

0 commit comments

Comments
 (0)