There’s a lot of controversial discussion over the internet about achieving accurate sleep function on Windows platforms. The problem is most of them are very old and with the introduction of multicore processors many of the older functions break down but this is not the case in 2023.
Nowadays you can easily call the cross-platform C++ 11 chrono function and with the following source code, I could achieve one millisecond accuracy which is more than enough for my application.
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::microseconds(500));
Before I used the QThread::msleep
function which had an accuracy of about 5ms
to 15ms
which was a lot more than what I imagined even when I used the QThread::usleep
function.
There is an issue that is if you call the sleep function on a thread the OS scheduling system will put your application to sleep and it may take a while till the scheduler picks up your application again. To prevent this issue you need to specifically tell OS to treat your application differently than others and C++ 11 introduces chrono which uses QueryPerformanceCounter
in the background Windows API to make sure Windows scheduler will pick your application up at the right time
You can go ahead and directly call the Windows API function but nowadays C++ 11 is nicely integrated into a lot of environments and it’s also a cross-platform solution so lucky you, you don’t need to get your hands dirty anymore.