Make clock fall back to REALTIME when MONOTONIC isn't supported

This commit is contained in:
MysterD 2021-08-09 23:58:05 -07:00
parent d772764c4e
commit 7044485431

View file

@ -1,3 +1,5 @@
#include <stdio.h>
#include <stdlib.h>
#include <PR/ultratypes.h>
#include <stdbool.h>
#include <time.h>
@ -23,18 +25,43 @@ void update_all_mario_stars(void) {
}
}
static void _clock_gettime(struct timespec* clock_time) {
#if !defined _POSIX_MONOTONIC_CLOCK || _POSIX_MONOTONIC_CLOCK < 0
clock_gettime(CLOCK_REALTIME, clock_time);
#elif _POSIX_MONOTONIC_CLOCK > 0
clock_gettime(CLOCK_MONOTONIC, clock_time);
#else
if (clock_gettime(CLOCK_MONOTONIC, clock_time))
clock_gettime(CLOCK_REALTIME, clock_time));
#endif
#ifdef DEVELOPMENT
// give each instance a random offset for testing purposed
static int randomOffset1 = 0;
static int randomOffset2 = 0;
if (randomOffset1 == 0) {
time_t t;
srand((unsigned)time(&t));
randomOffset1 = rand();
randomOffset2 = rand();
}
clock_time->tv_sec += randomOffset1;
clock_time->tv_nsec += randomOffset2;
#endif
}
static u64 clock_elapsed_ns(void) {
static bool sClockInitialized = false;
static u64 clock_start_ns;
if (!sClockInitialized) {
struct timespec clock_start;
clock_gettime(CLOCK_MONOTONIC, &clock_start);
_clock_gettime(&clock_start);
clock_start_ns = ((u64)clock_start.tv_sec) * 1000000000 + clock_start.tv_nsec;
sClockInitialized = true;
}
struct timespec clock_current;
clock_gettime(CLOCK_MONOTONIC, &clock_current);
_clock_gettime(&clock_current);
u64 clock_current_ns = ((u64)clock_current.tv_sec) * 1000000000 + clock_current.tv_nsec;
return (clock_current_ns - clock_start_ns);