C++

How to Master Time-Sensitive Tasks with Sleep for Milliseconds in C++

Many programming applications rely on time-sensitive tasks, and C++ provides a powerful set of tools to manage them efficiently. The Sleep() function, which allows programmers to halt the execution of a program for a particular amount of time, is one of the most basic methods for controlling time-sensitive tasks in C++. The Sleep feature is very useful when a program needs to complete a task after a certain amount of time, wait for input, or synchronize with other processes.

In this guide, we will look at how to use the sleep for milliseconds in C++ to efficiently master time-sensitive tasks.

Sleep for Milliseconds in C++

In C++, there are several functions available to sleep for milliseconds, each with different characteristics and usage scenarios. Here are some of the most used functions:

1: std::this_thread::sleep_for()

The std::this_thread::sleep_for() function is a C++11 standard library function that allows you to temporarily halt the execution of a thread. The duration is supplied using the std::chrono::duration template class, which specifies a length of time in milliseconds, seconds, minutes, and so on.

To use the std::this_thread::sleep_for() function to stop code execution for a set period of time, pass it an argument of type std::chrono::milliseconds, which indicates a time duration in milliseconds.

For example, to block the code execution for 3000 milliseconds, you can use the following code:

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

int main()
{
    cout << "Hello...." << endl;
    this_thread::sleep_for(chrono::milliseconds(3000) );
    cout << "Waited 3000 ms\n";
    cout << "Hello Linuxhint\n";
}

The above C++ program prints “Hello….”, wait for 3000 milliseconds using this_thread::sleep_for(), prints “Waited 3000 ms”, and finally prints “Hello Linuxhint”.

Output

In another example we have delayed the process of the loop for 3000 milliseconds using the same function:

#include<iostream>
#include <chrono>
#include <thread>
using std::cout;
using std::cin;
using std::endl;
using std::this_thread::sleep_for;

constexpr int TIME_TO_SLEEP = 3000;

int main() {
    cout << "Started loop.." << endl;
    for (int i = 0; i < 10; ++i) {
    cout << "Iteration - " << i << endl;

        if (i == 4) {

            cout << "Sleeping ...." << endl;
            sleep_for(std::chrono::milliseconds(TIME_TO_SLEEP));
        }
    }
    return 0;
}

The above C++ program starts a loop that iterates five times, printing the current iteration number each time. On the fourth iteration, the program sleeps for 3000 milliseconds (3 seconds) using this_thread::sleep_for(). After sleeping, the program continues the loop and prints the remaining iteration numbers.

Output

 

2: Sleep() Function

The Sleep() function is a part of Windows API and is available only on Windows systems. It suspends the execution of the current thread for the specified number of milliseconds. You can also use this function in your C++ program to sleep a specific thread for milliseconds. The sleep function takes one parameter the time for delaying the thread or a process. The sleep will delay a specific thread only in C++ and the other programs on the CPU will work properly. You have to use the two libraries at the top of the header according to the system you are using. If you are using a Windows laptop add the following two libraries:

#ifdef _WIN32
#include <Windows.h>

The value provided in the Sleep() function is in milliseconds like 3000 milliseconds is equal to 3 seconds. In the below-written code, I have added the delay between the hello and world statement through the sleep function:

#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout << "Hello\n";
    cout.flush();
    Sleep(1000); // Sleep for 3000 milliseconds
    cout << "Wait for 3000milliseconds\n";
    cout << "World";
    cout << endl;

    return 0;
}
#endif

The above C++ code uses the Sleep() function from the Windows API to pause the execution of the program for 3000 milliseconds (3 seconds). The cout function ensures that the message “Hello” is printed to the console immediately before the program sleeps. The code is enclosed in an #ifdef _WIN32 preprocessor directive to ensure that it will only be compiled on Windows systems.

Output

Bottom Line

C++ provides various options for controlling time-sensitive tasks. The std::this_thread::sleep_for() and Sleep functions are some of the commonly used functions to delay the execution of a program for a specific amount of time. While std::this_thread::sleep_for() is a standard C++ function that can be used on multiple platforms, Sleep() is a Windows API function and is only available on Windows systems. Programmers can choose the appropriate function based on their requirements and the platform they are working on.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.