+#ifdef WIN32
+static LARGE_INTEGER PerformanceFreq;
+/// Windows default timer resolution is only 15.625ms,
+/// this affects (at least) timeGetTime() and all forms of sleeping.
+static void Sys_SetTimerResolution(void)
+{
+ NTSTATUS(NTAPI *qNtQueryTimerResolution)(OUT PULONG MinRes, OUT PULONG MaxRes, OUT PULONG CurrentRes);
+ NTSTATUS(NTAPI *qNtSetTimerResolution)(IN ULONG DesiredRes, IN BOOLEAN SetRes, OUT PULONG ActualRes);
+ const char* ntdll_names [] =
+ {
+ "ntdll.dll",
+ NULL
+ };
+ dllfunction_t ntdll_funcs[] =
+ {
+ {"NtQueryTimerResolution", (void **) &qNtQueryTimerResolution},
+ {"NtSetTimerResolution", (void **) &qNtSetTimerResolution},
+ {NULL, NULL}
+ };
+ dllhandle_t ntdll;
+ unsigned long WorstRes, BestRes, CurrentRes;
+
+ timeBeginPeriod(1); // 1ms, documented
+
+ // the best Windows can manage (typically 0.5ms)
+ // http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FTime%2FNtSetTimerResolution.html
+ if (Sys_LoadDependency(ntdll_names, &ntdll, ntdll_funcs))
+ {
+ qNtQueryTimerResolution(&WorstRes, &BestRes, &CurrentRes); // no pointers may be NULL
+ if (CurrentRes > BestRes)
+ qNtSetTimerResolution(BestRes, true, &CurrentRes);
+
+ Sys_FreeLibrary(&ntdll);
+ }
+
+ // Microsoft says the freq is fixed at boot and consistent across all processors
+ // and that it need only be queried once and cached.
+ QueryPerformanceFrequency (&PerformanceFreq);
+}
+#endif // WIN32
+