From 4f44c633a22a0da0fa48147d0da0ffd7a531e316 Mon Sep 17 00:00:00 2001 From: wutno Date: Mon, 16 Oct 2023 07:25:24 -0400 Subject: [PATCH] winapi: Allow dynamic calculation of CPU frequency for QueryPerformanceFrequency --- lib/winapi/profiling.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib/winapi/profiling.c b/lib/winapi/profiling.c index bdea7cc0a..6b11ebc8a 100644 --- a/lib/winapi/profiling.c +++ b/lib/winapi/profiling.c @@ -3,6 +3,9 @@ // SPDX-FileCopyrightText: 2019 Stefan Schmidt #include +#ifdef USE_RDTSC_FOR_FREQ +#include +#endif #include #include #include @@ -19,6 +22,36 @@ BOOL QueryPerformanceFrequency (LARGE_INTEGER *lpFrequency) { assert(lpFrequency != NULL); +#ifdef USE_RDTSC_FOR_FREQ + #define AVG_SET 10 + ULARGE_INTEGER f_rdtsc, avg; + ULONG f_ticks = 0; + + avg.QuadPart = 0; + + for (int i = 0; i < AVG_SET; i++) { + ULARGE_INTEGER s_rdtsc; + ULONG s_ticks; + + s_rdtsc.QuadPart = __rdtsc(); + s_ticks = KeTickCount; + + s_rdtsc.QuadPart -= f_rdtsc.QuadPart; + s_rdtsc.QuadPart /= s_ticks - f_ticks; + + f_rdtsc.QuadPart = __rdtsc(); + f_ticks = KeTickCount; + + // Skip the first result as invalid + if (i) + avg.QuadPart += s_rdtsc.QuadPart; + + // If we call rdtsc too fast we'll end up with div by 0 + Sleep(10); + } + lpFrequency->QuadPart = (avg.QuadPart / (AVG_SET - 1)) * 1000; +#else lpFrequency->QuadPart = 733333333; +#endif return TRUE; } \ No newline at end of file