From cc945cad053cd36d67ee5daf50a71e212ce2cfe3 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Tue, 8 Jul 2025 08:39:27 -0700 Subject: Fixes, add time_add --- timer/include/timer.h | 5 ++++- timer/src/timer.c | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/timer/include/timer.h b/timer/include/timer.h index 94781d6..6dc87d9 100644 --- a/timer/include/timer.h +++ b/timer/include/timer.h @@ -20,7 +20,7 @@ typedef struct timespec time_point; typedef uint64_t time_delta; /// A high resolution timer. -typedef struct { +typedef struct Timer { time_point start_time; // The instant the timer was last started. time_point last_tick; // The instant the timer was last ticked. time_delta running_time; // Time elapsed since the timer was last started. @@ -53,6 +53,9 @@ time_delta sec_to_time_delta(double seconds); /// Convert the time point to nanoseconds. uint64_t time_point_to_ns(time_point); +/// Add a time delta to a timestamp. +time_point time_add(time_point, time_delta); + /// Put the caller thread to sleep for the given amount of time. void time_sleep(time_delta dt); diff --git a/timer/src/timer.c b/timer/src/timer.c index 340cd98..d886f59 100644 --- a/timer/src/timer.c +++ b/timer/src/timer.c @@ -78,7 +78,7 @@ time_delta sec_to_time_delta(double seconds) { #ifdef _WIN32 return (time_delta)(seconds / seconds_per_count); #else - return (time_delta)(seconds * nanoseconds); + return (time_delta)(seconds * 1.0e9); #endif } @@ -90,9 +90,20 @@ uint64_t time_point_to_ns(time_point t) { #endif } +time_point time_add(time_point t, time_delta dt) { + time_point out; +#ifdef _WIN32 + out = t + dt; +#else + out.tv_sec = t.tv_sec + (__time_t)(dt / nanoseconds); + out.tv_nsec = t.tv_nsec + (__time_t)(dt % nanoseconds); +#endif + return out; +} + void time_sleep(time_delta dt) { #ifdef _WIN32 - const int64_t ms = dt / microseconds; + const uint64_t ms = dt / microseconds; Sleep((DWORD)(ms)); #else const uint64_t sec = dt / nanoseconds; -- cgit v1.2.3