Cross platform Sleep function for C++

Yup. But this only works in C++11 and later. #include <chrono> #include <thread> … std::this_thread::sleep_for(std::chrono::milliseconds(ms)); where ms is the amount of time you want to sleep in milliseconds. You can also replace milliseconds with nanoseconds, microseconds, seconds, minutes, or hours. (These are specializations of the type std::chrono::duration.) Update: In C++14, if you’re sleeping for a … Read more

Why does Sleep(500) cost more than 500ms?

Because Win32 API’s Sleep isn’t a high-precision sleep, and has a maximum granularity. The best way to get a precision sleep is to sleep a bit less (~50 ms) and do a busy-wait. To find the exact amount of time you need to busywait, get the resolution of the system clock using timeGetDevCaps and multiply … Read more

Significance of Sleep(0)

According to MSDN’s documentation for Sleep: A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution. The important thing to realize is that … Read more

Compare using Thread.Sleep and Timer for delayed execution

One difference is that System.Threading.Timer dispatches the callback on a thread pool thread, rather than creating a new thread every time. If you need this to happen more than once during the life of your application, this will save the overhead of creating and destroying a bunch of threads (a process which is very resource … Read more