0

I need to find the most reliable/stable (against spurious wakeups, scheduling or resource contention delays, etc) way in C++ to sleep for a specific time duration (in my case, given as a number of seconds expressed as a floating point number). I have 3 ideas, but please feel free to suggest more. Please, let me know if any of the 3 methods proposed below is better than the others and why:

#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>

using Time = double;
const Time sleepTime = 777.7; // some number of seconds

using Clock     = std::chrono::steady_clock;
using ClockTime = std::chrono::time_point<Clock>;

const auto sleepDuration = std::chrono::duration_cast<Clock::duration>(
    std::chrono::duration<Time>( sleepTime ));
const ClockTime timeout = Clock::now() + sleepDuration;

// method 1
std::mutex mutex;
std::unique_lock lock(mutex);
std::condition_variable cond;
while(true) if(cond.wait_until(lock, timeout)==std::cv_status::timeout) break;

// method 2
std::this_thread::sleep_until(timeout);

// method 3
std::this_thread::sleep_for(sleepDuration);

Thank you very much for your help!

S.V
  • 2,149
  • 2
  • 18
  • 41
  • its largely OS dependant but I'd imagine all of the above will yield similar results (have you tried them?). In a non real-time OS the most reliable option is often to have a high priority process and spin until the desired time is reached. How accurate do you need the timing to be? – Alan Birtles Nov 01 '21 at 20:53
  • The current application of the code needs accuracy much smaller than a millisecond. Future applications will need a microsecond or less accuracy. So, basically, I need it to be as accurate as possible. I could also have several sleep methods implemented for different applications. – S.V Nov 01 '21 at 20:58
  • What will sleepTime actually be? I'm thinking probably not 777 seconds, to an accuracy of a microsecond or less. Fundamentally what you are describing belongs in the realm of dedicated hardware, not PC's with traditional operating systems. – ttemple Nov 01 '21 at 22:05

0 Answers0