-
Notifications
You must be signed in to change notification settings - Fork 0
/
windows-millisleep.cpp
55 lines (41 loc) · 1.56 KB
/
windows-millisleep.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <Windows.h>
#define WIN32_LEAN_AND_MEAN
enum SLP_ENUM { SLP_SUCCESS, SLP_INVAL, SLP_INTR };
extern "C"
{
__declspec(dllexport) __int32 linux_millisleep(__int32 milliseconds)
{
static bool initialized;
static double ticks_per_millisec;
if (milliseconds < 0)
return SLP_INVAL;
// for delays longer than 10 seconds, ignore the delay
if (milliseconds > (1000 * 10)) {
Sleep(milliseconds);
} else {
if (!initialized) {
LARGE_INTEGER ticks_per_sec;
if (QueryPerformanceFrequency(&ticks_per_sec))
ticks_per_millisec = (double) ticks_per_sec.QuadPart / 1000000.0;
initialized = true;
}
__int32 sleep_millis = (__int32) milliseconds - 16;
__int64 wait_ticks = milliseconds * ticks_per_millisec;
LARGE_INTEGER counter_before;
if (QueryPerformanceCounter(&counter_before)) {
__int64 wait_until = counter_before.QuadPart + wait_ticks;
if (sleep_millis > 0)
Sleep(sleep_millis);
LARGE_INTEGER counter_after;
while (1) {
// if query failed
if (!QueryPerformanceCounter(&counter_after))
break;
if (counter_after.QuadPart >= wait_until)
break;
}
}
}
return SLP_SUCCESS;
}
}