From 3f05df3fbb157a8db6bbead4f0193f6d9d76626d Mon Sep 17 00:00:00 2001 From: chao an Date: Mon, 10 Apr 2023 22:24:19 +0800 Subject: [PATCH] sim/win/hosttime: calculate sec/ms independently to avoid overflow In the previous implementation, PerformanceCounter would cause overflow after running for a long time, This commit will separate the calculation of the sec/ms part to avoid this issue, Reference: https://github.com/cygwin/cygwin/blob/main/winsup/cygwin/clock.cc#L194-L217 Signed-off-by: chao an --- arch/sim/src/sim/win/sim_hosttime.c | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/arch/sim/src/sim/win/sim_hosttime.c b/arch/sim/src/sim/win/sim_hosttime.c index db0b23e0da..2323f5f438 100644 --- a/arch/sim/src/sim/win/sim_hosttime.c +++ b/arch/sim/src/sim/win/sim_hosttime.c @@ -48,9 +48,10 @@ uint64_t host_gettime(bool rtc) { - static LARGE_INTEGER start; - LARGE_INTEGER counter; - LARGE_INTEGER freq; + static long long int ticks_per_sec; + static uint64_t start; + uint64_t current; + LARGE_INTEGER now; FILETIME ftime; if (rtc) @@ -61,17 +62,23 @@ uint64_t host_gettime(bool rtc) ftime.dwLowDateTime) - DELTA_EPOCH_IN_100NS) * 100; } - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&counter); - - counter.QuadPart = counter.QuadPart * POW10_9 / freq.QuadPart; - - if (start.QuadPart == 0) + if (ticks_per_sec == 0) { - start.QuadPart = counter.QuadPart; + QueryPerformanceFrequency(&now); + InterlockedExchange64(&ticks_per_sec, now.QuadPart); } - return counter.QuadPart - start.QuadPart; + QueryPerformanceCounter(&now); + + current = now.QuadPart / ticks_per_sec * POW10_9 + + (now.QuadPart % ticks_per_sec) * POW10_9 / ticks_per_sec; + + if (start == 0) + { + start = current; + } + + return current - start; } /****************************************************************************