Skip to content

Instantly share code, notes, and snippets.

@Tapanhaz
Forked from ngryman/usleep.c
Created March 9, 2025 20:51
Show Gist options
  • Select an option

  • Save Tapanhaz/9bb72a98ed49d19d7320fda3c43990b0 to your computer and use it in GitHub Desktop.

Select an option

Save Tapanhaz/9bb72a98ed49d19d7320fda3c43990b0 to your computer and use it in GitHub Desktop.
usleep for Windows.
void usleep(DWORD waitTime){
LARGE_INTEGER perfCnt, start, now;
QueryPerformanceFrequency(&perfCnt);
QueryPerformanceCounter(&start);
do {
QueryPerformanceCounter((LARGE_INTEGER*) &now);
} while ((now.QuadPart - start.QuadPart) / float(perfCnt.QuadPart) * 1000 * 1000 < waitTime);
}
@Tapanhaz
Copy link
Author

Tapanhaz commented Mar 9, 2025

https://gist.github.com/ngryman/6482577?permalink_comment_id=2637845#gistcomment-2637845
'''

Use a waitable timer. This code above creates a spinlock.

portable c++11:

#include
#include `
std::this_thread::sleep_for(std::chrono::microseconds(usec));

portable boost for old compilers:

#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
boost::this_thread::sleep(boost::posix_time::microseconds(usec));

using plain Win32API:

void usleep(unsigned int usec)
{
HANDLE timer;
LARGE_INTEGER ft;

ft.QuadPart = -(10 * (__int64)usec);

timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);

}

'''

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