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!