Sleep for milliseconds
#1
I've been working on a project where precise timing is critical. Typically, in Unix-based systems, I might use the `sleep` function provided by `unistd.h` to pause a program's execution, but it only supports second-level granularity. Now, I need a way to put the thread to sleep for a specified number of milliseconds. From what I've read, C++11 introduces some new features in the `<thread>` and `<chrono>` libraries that might be useful. However, I'm not too familiar with these yet. Can someone help to provide a code snippet to accomplish a millisecond sleep using C++11 or later standards? Here's a basic idea of what I've been attempting:

Code:
int main() {
    sleep(1); // sleeps for 1 second
    return 0;
}

I understand that to use milliseconds, I'll have to move away from `sleep` and towards something more granular. What is the optimal way to handle this in modern C++?
Reply
#2
In C++11 and later, you can use the `<chrono>` and `<thread>` libraries for this purpose. The function you are looking for is `std::this_thread:Confusedleep_for()`. It takes a duration as its argument. Here's an example showing how to make the program sleep for 100 milliseconds:

Code:
#include <thread>

int main() {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return 0;
}

When you use `std::chrono::milliseconds`, it defines the period in milliseconds and `std::this_thread:Confusedleep_for` takes care of the rest. It's a standard way to handle precise sleep intervals in modern C++.
Reply
#3
That's correct. Additionally, remember that the actual sleep time may be longer than requested due to the scheduling of other activities in the system. To ensure even more precise timing, you may need to consider real-time features or high-resolution timers in your system, which are beyond the scope of standard C++. However, for most applications where a simple sleep is required, `std::this_thread:Confusedleep_for` with `<chrono>` durations is sufficient. In case you need a higher precision, investigate platform-specific APIs or hardware timers.
Reply
#4
Indeed. If you are running a real-time system or high-performance computing application where precision and accuracy down to the microsecond or nanosecond are required, you might need to look into system-specific solutions or hardware-dependent APIs that can offer more precise timing functionalities. Nevertheless, the introduced `std::this_thread:Confusedleep_for` with `<chrono>` is suitable for common use cases.
To summarize, here's the code you can run to make a program sleep for 100 milliseconds in C++:

Code:
#include <thread>

int main() {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return 0;
}

Make sure to compile your program with a C++11 or later standard using the `-std=c++11` flag, like so:

Code:
sh
g++ - std = c++11 your_program.cpp - o your_program
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)