Skip to content

Instantly share code, notes, and snippets.

@sturlamolden
Last active January 12, 2016 22:48
Show Gist options
  • Save sturlamolden/351c111141380bd203bf to your computer and use it in GitHub Desktop.
Save sturlamolden/351c111141380bd203bf to your computer and use it in GitHub Desktop.
#include <Windows.h>
#include <mmsystem.h>
#include <math.h>
static BOOL inited = FALSE;
static double dhz;
void usleep( long us )
{
const double sleep_granularity = 2.0E-3;
__int64 cnt, end;
double diff;
if (!inited) {
__int64 hz;
timeBeginPeriod(1);
QueryPerformanceFrequency((LARGE_INTEGER*)&hz);
dhz = (double)hz;
inited = TRUE;
}
QueryPerformanceCounter((LARGE_INTEGER*)&cnt);
end = cnt + (__int64)ceil(1.0E-6 * (double)(us) * dhz);
for (;;) {
QueryPerformanceCounter((LARGE_INTEGER*)&cnt);
if (cnt >= end) break;
diff = (double)(end - cnt)/dhz;
if (diff > sleep_granularity)
Sleep((DWORD)floor(1000 * (diff - sleep_granularity)));
else
Sleep(0); /* yields the cpu */
}
}
@sturlamolden
Copy link
Author

Emulation of Unix usleep function in Windows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment