Skip to content

Instantly share code, notes, and snippets.

@ngryman
Created September 8, 2013 07:07
Show Gist options
  • Save ngryman/6482577 to your computer and use it in GitHub Desktop.
Save ngryman/6482577 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);
}
@latsa
Copy link

latsa commented Jul 4, 2018

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

portable c++11:

#include <chrono>
#include <thread>`
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);
}

@cidzoo
Copy link

cidzoo commented Dec 5, 2018

Caution: this gist snippet from @ngryman will do busy waiting, it may not be what you want!

Can't agree more with @latsa, and thanks for the much more efficient plain Win32 API version.

@DanielGibson
Copy link

DanielGibson commented Jan 26, 2023

With @latsa's solutions (at least std::this_thread::sleep_for() and WaitForSingleObject(), I'm not using boost), even usleep(1) takes at least 10-15ms or so on my Win10 machine, which makes microsecond granularity kinda pointless..
Calling timeBeginPeriod(1); at the beginning of the program makes Sleep(1) take about 2ms instead of 15ms; with the WaitForSingleObject() method I can even get down to 1ms, but not below.

The busy waiting can be made a bit more CPU-friendly by inserting calls to _mm_pause() (that won't decrease the CPU usage that the task manager shows, but the CPU will run at a slighly lower temperature, or at least it did on my machine when inserting like 20 calls to _mm_pause() in between calls to QueryPerformanceCounter())

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