The process to add a timed delay in a C++ application is explained in depth in this tutorial.
How Can a Timed Delay Be Added to a C++ Program
There are two methods to add a time delay in C++, which are as follows:
Method 1: Add a Time Delay in C++ Using sleep() Function
The sleep() is one of the functions that adds a time delay in between the outputs. You must define a time according to your desire inside the closing bracket of sleep(). The function only accepts one argument, which is the duration of the program’s pause in seconds. After the delay is finished, the program continues from where it left off. This makes it particularly useful for introducing a set amount of time between instructions or iterations of an algorithm. When the sleep() command is used in a program, it should always be used in conjunction with other commands in the program. This is to ensure that the delay does not interfere with the rest of the program, as the sleep() command will cause the program to run more slowly.
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main()
{
cout<<"Before sleep call"<<endl;
cout.flush();
sleep(5);
cout<<"after"<<endl;
return 0;
}
In this code, we are importing the necessary libraries we need to use for the sleep() function, and then we are printing the ‘Before sleep call’ before calling the sleep() function. And the next output is printed after 5 seconds (i.e., given time as an argument in the sleep() function).
Output
You can see in the outputs that the statement is printed after 5 seconds.
Method 2: Add a Time Delay in C++ Using usleep() function
If a delay of less than a single second is needed, the usleep() function must be used. Unlike sleep(), which requires the argument in seconds, usleep() requires the argument to be in microseconds. To use it, the argument is divided by 1,000,000 and the decimal is discarded.
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main()
{
cout<<"Before sleep call"<<endl;
cout.flush();
usleep(10000000);
cout<<"after"<<endl;
return 0;
}
This code imports the necessary libraries for the usleep() function, and before executing the usleep() method, it prints the words “Before sleep call.” After 10 seconds, the following output is produced (i.e., time is specified as an input, in microseconds, in the usleep() method).
Output
The outputs show that after 10 seconds, the sentence is printed.
Conclusion
To add a time delay in between the outputs, the users can use the sleep() and usleep() functions. The sleep function takes the arguments in seconds, while usleep function takes the arguments in microseconds. It’s up to the user what function they want to use because both can easily be included in the C++ code.