diff options
Diffstat (limited to 'Spear/Sys/Timer/timer.h')
| -rw-r--r-- | Spear/Sys/Timer/timer.h | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/Spear/Sys/Timer/timer.h b/Spear/Sys/Timer/timer.h new file mode 100644 index 0000000..e426135 --- /dev/null +++ b/Spear/Sys/Timer/timer.h | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | #include <stdint.h> | ||
| 4 | |||
| 5 | /// A particular point in time. | ||
| 6 | #ifdef _WIN32 | ||
| 7 | typedef uint64_t time_point; | ||
| 8 | #else | ||
| 9 | // Need to macro to make CLOCK_REALTIME available when compiling with ISO C11. | ||
| 10 | // The constant is only needed in the source file, but the header file needs to | ||
| 11 | // include time.h too. | ||
| 12 | #ifndef __USE_POSIX199309 | ||
| 13 | #define __USE_POSIX199309 | ||
| 14 | #endif // | ||
| 15 | #include <time.h> | ||
| 16 | typedef struct timespec time_point; | ||
| 17 | #endif | ||
| 18 | |||
| 19 | /// Time elapsed between two time points. | ||
| 20 | typedef uint64_t time_delta; | ||
| 21 | |||
| 22 | /// A high resolution timer. | ||
| 23 | typedef struct Timer { | ||
| 24 | time_point start_time; // The instant the timer was last started. | ||
| 25 | time_point last_tick; // The instant the timer was last ticked. | ||
| 26 | time_delta running_time; // Time elapsed since the timer was last started. | ||
| 27 | time_delta delta_time; // Time elapsed since the last tick. | ||
| 28 | } Timer; | ||
| 29 | |||
| 30 | /// Construct a new timer. | ||
| 31 | void timer_make(Timer*); | ||
| 32 | |||
| 33 | /// Start the timer. | ||
| 34 | /// This sets the time point from which time deltas are measured. | ||
| 35 | /// Calling this multilple times resets the timer. | ||
| 36 | void timer_start(Timer*); | ||
| 37 | |||
| 38 | /// Update the timer's running and delta times. | ||
| 39 | void timer_tick(Timer*); | ||
| 40 | |||
| 41 | /// Get the current time. | ||
| 42 | void time_now(time_point*); | ||
| 43 | |||
| 44 | /// Return the time elapsed between two timestamps. | ||
| 45 | time_delta time_diff(time_point* start, time_point* end); | ||
| 46 | |||
| 47 | /// Return the time elapsed in seconds. | ||
| 48 | double time_delta_to_sec(time_delta dt); | ||
| 49 | |||
| 50 | /// Convert the time elapsed in seconds to a time delta. | ||
| 51 | time_delta sec_to_time_delta(double seconds); | ||
| 52 | |||
| 53 | /// Convert the time point to nanoseconds. | ||
| 54 | uint64_t time_point_to_ns(time_point*); | ||
| 55 | |||
| 56 | /// Put the caller thread to sleep for the given amount of time. | ||
| 57 | void time_sleep(time_delta dt); | ||
| 58 | |||
| 59 | /// The time point 0. | ||
| 60 | #ifdef _WIN32 | ||
| 61 | static const time_point time_zero = 0; | ||
| 62 | #else | ||
| 63 | static const time_point time_zero = {0, 0}; | ||
| 64 | #endif | ||
