From 87529f37c83a623e317e38afa1b4dba809d37797 Mon Sep 17 00:00:00 2001 From: fgsfds Date: Thu, 24 Aug 2023 18:11:14 +0200 Subject: [PATCH] port: use gettimeofday() as timing source; use smaller tick multiplier to avoid overflows --- port/include/system.h | 4 ++-- port/src/libultra.c | 5 ++++- port/src/main.c | 1 + port/src/system.c | 26 +++++++++----------------- 4 files changed, 16 insertions(+), 20 deletions(-) diff --git a/port/include/system.h b/port/include/system.h index 2159d92fb..4d99842b7 100644 --- a/port/include/system.h +++ b/port/include/system.h @@ -3,8 +3,8 @@ #include -u64 sysGetTicks(void); -u64 sysGetTicksPerSecond(void); +void sysInitTicks(void); +u64 sysGetMicroseconds(void); void sysFatalError(const char *fmt, ...) __attribute__((noreturn)); diff --git a/port/src/libultra.c b/port/src/libultra.c index 469c7d77a..b8da8ed60 100644 --- a/port/src/libultra.c +++ b/port/src/libultra.c @@ -15,6 +15,9 @@ #define EEPROM_FNAME "./eeprom.bin" #define OS_COUNTER_RATE 46875000ULL +#define OS_COUNTER_NUM (OS_COUNTER_RATE / 1000ULL) +#define OS_COUNTER_DEN (1000000ULL / 1000ULL) + u64 osClockRate = OS_CLOCK_RATE; u32 osMemSize = 16 * 1024 * 1024; /* expansion pak installed plus some extra */ s32 osTvType = OS_TV_NTSC; /* 0 = PAL, 1 = NTSC, 2 = MPAL */ @@ -26,7 +29,7 @@ s32 osViClock = VI_NTSC_CLOCK; OSTime osGetTime(void) { // u64 should be enough to last a while - return (sysGetTicks() * OS_COUNTER_RATE) / sysGetTicksPerSecond(); + return (sysGetMicroseconds() * OS_COUNTER_NUM) / OS_COUNTER_DEN; } u32 osGetCount(void) diff --git a/port/src/main.c b/port/src/main.c index 994de5c5b..4a0178dec 100644 --- a/port/src/main.c +++ b/port/src/main.c @@ -60,6 +60,7 @@ static void cleanup(void) int main(int argc, const char **argv) { + sysInitTicks(); fsInit(); configInit(); videoInit(); diff --git a/port/src/system.c b/port/src/system.c index da5c33f8e..5fd2977f3 100644 --- a/port/src/system.c +++ b/port/src/system.c @@ -2,33 +2,25 @@ #include #include #include +#include #include #include #include "system.h" +#define USEC_IN_SEC 1000000ULL + static u64 startTick = 0; -static u64 tickFreq = 0; -static void sysInitTicks(void) +void sysInitTicks(void) { - tickFreq = SDL_GetPerformanceFrequency(); - startTick = SDL_GetPerformanceCounter(); + startTick = sysGetMicroseconds(); } -u64 sysGetTicks(void) +u64 sysGetMicroseconds(void) { - if (tickFreq == 0) { - sysInitTicks(); - } - return (SDL_GetPerformanceCounter() - startTick); -} - -u64 sysGetTicksPerSecond(void) -{ - if (tickFreq == 0) { - sysInitTicks(); - } - return tickFreq; + struct timeval tv; + gettimeofday(&tv, NULL); + return ((u64)tv.tv_sec * USEC_IN_SEC + (u64)tv.tv_usec) - startTick; } void sysFatalError(const char *fmt, ...)