c++, usleep() is obsolete, workarounds for Windows/MingW?

I used this code from (originally from here):

#include <windows.h>

void usleep(__int64 usec) 
{ 
    HANDLE timer; 
    LARGE_INTEGER ft; 

    ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time

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

Note that SetWaitableTimer() uses “100 nanosecond intervals … Positive values indicate absolute time. … Negative values indicate relative time.” and that “The actual timer accuracy depends on the capability of your hardware.

If you have a C++11 compiler then you can use this portable version:

#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::microseconds(usec));

Kudos to Howard Hinnant who designed the amazing <chrono> library (and whose answer below deserves more love.)

If you don’t have C++11, but you have boost, then you can do this instead:

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

Leave a Comment