I'm trying to add a time delay to a c program and i was wondering if anyone has suggestions on what i can try or information i can look

I'd like to know more details on how i'm implementing this timed delay but until i know more about how to add a timed delay i'm not sure how i should even attempt to implement this

Best Answer


A revised answer for the c11 exam

Use the sleep_for and sleep_until functions.

#include <chrono>
#include <thread>

int main() {
    using namespace std::this_thread; // sleep_for, sleep_until
    using namespace std::chrono; // nanoseconds, system_clock, seconds

    sleep_for(nanoseconds(10));
    sleep_until(system_clock::now() + seconds(1));
}

With these functions there's no longer a need to continually add new functions for better resolution: sleep , usleep , nanosleep , etc. sleep_for and sleep_until are template functions that can accept values of any resolution via chrono types; hours, seconds, femtoseconds, etc.

In C++14 you can further simplify the code with the literal suffixes for nanoseconds and seconds .

#include <chrono>
#include <thread>

int main() {
    using namespace std::this_thread;     // sleep_for, sleep_until
    using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
    using std::chrono::system_clock;

    sleep_for(10ns);
    sleep_until(system_clock::now() + 1s);
}

Note that the actual duration of a sleep depends on the implementation: you can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that's the shortest it can do.