Sleep function in cpp

3 Examples to Understand C++ Sleep(), usleep(), sleep_for() Functions

In this tutorial, we will learn how to delay the execution of code in C++ programs. The following functions are explained with examples below:

What is Sleep function in C++

  • To delay the execution of C++ program, we can use the Sleep() function.
  • The Sleep() function is part of Windows.h header file, so you should use other functions for cross-platform compatibility.
  • The value provided in the Sleep() function is in milliseconds. i.e. 1000 = 1 second

Sleep_for – Other function for delay in execution of C++ program or thread

You may use other functions for cross-platform compatibility. One of the functions is:

This is part of chrono library, so you have to include this in the header section.

Читайте также:  Windows планировщик задач php

Note: This function is only available from C++ 11 and onwards.

An example of C++ Sleep function for windows

In this example to explain how C++ Sleep function works, we have used a for loop. The loop iterates five times and in each iteration the Sleep function is executed to delay the execution by 1000 milliseconds (i.e. one second).

CPP-Sleep

In the above output, you can see the execution time is around 5 seconds.

To show the difference, I just disabled the following in the above code i.e:

CPP-Sleep-disabled

You can see, it only took 0.008 seconds to execute the above program.

Copy/Paste the above programs and execute them in your own editor to see this working.

An example of using sleep_for() function for Linux (cross-platform)

We are again using the for loop to iterate ten times to demonstrate the sleep_for function in C++. To show the difference we will run the program with and without the sleep_for() and you can notice the execution time difference in both programs.

C++ program with sleep_for() function:

Источник

C++ Sleep Function: Syntax & Examples (sleep for milliseconds)

C++ Sleep Function: Syntax & Examples (sleep for milliseconds)

In this article, we are going to deep dive into the sleep function in C++, its syntax, and examples with code. There are numerous operations provided by the operating system to us, one of them is the sleep() function.

Before going into detail, let’s just first cover the basic terminologies we will use in between. But we need to revise some prerequisites like process and threads first.

Process vs Thread

Let’s check the easy definitions of both these terms.

The Process is a program in the execution phase or an instance of a program that is being executed or processed is called Process. Thread is a segment of a process or a lightweight process that is managed by the scheduler independently.

Please remember that processes are independent of each other and hence don’t share a memory or other resources. On the other hand, threads are interdependent and share memory.

Sleep Function in C++

Sleep function in C++ is used to suspend the execution of a thread or a process for a specified period of time temporarily. Other CPU operations will function adequately but sleep() will delay a specific thread only.

This sleep() function takes one single argument which specifies the time in seconds for which the execution of the thread or the process must be suspended. The thread or process continues to be delayed until the specified time is completed.

Also, note that we can interrupt the sleep() function in between by sending any interrupts to the function. If you are using Windows, must include the header file and if you are using Linux, then must include the header file at the top of your program.

So, it can be implemented using 2 libraries according to the operating system being used:

#include // for windows #include // for linux 

The execution of the current thread is stopped until at least time_period has passed from now. Other threads continue their execution.

Syntax:

sleep( time_period ); // time_period in seconds

Parameters and Return Type:

The sleep() function has only one parameter: time_period, which is the time span after which the calling thread shall resume its execution. Please note that Multi-threading management operations may cause certain delays beyond this.

The sleep returns an Integer. It returns 0 if the function is successfully executed, or else minus the value of the time period returned.

Examples of C++ thread sleep

Given below are the examples of C++ thread sleep:

Example 1

A C++ program to demonstrate the use of sleep() function:

// Welcome to FavTutor // C++ Program to show how to use // sleep function #include // Library effective with Windows #include // Library effective with Linux #include using namespace std; // Driver code int main() < cout  "Join the Line:\n"; cout  "Wait for 5 seconds\n"; // sleep will schedule rest of // activities after 10 seconds sleep(5); cout  "It's your time buy ticket"; >
Join the Line: Wait for 5 seconds It's your time buy ticket

In this example, we first included the 2 header files for windows and for Linux users. In the main function, the first cout statements will print first, and then the sleep() function will execute and delays the execution of the process by 5 seconds and after 5 seconds, the third cout will get printed.

Example 2

A C++ program to demonstrate the use of sleep() function:

// Welcome To FavTutor //the headers iostream and unistd are included to be able to make use of cout and cin statements and sleep() function #include #include using namespace std; int main() < //The first cout statement is executed cout"Welcome""\n"; //Then the sleep() function is called before executing the next cout statement sleep(10); //this cout statement is executed after the sleep function is executed for the speicifed amount of time cout"to C++"; coutendl; return 0; >

In this example, we included first the required header file, here , first, cout will print initially, and then the sleep() function executes for 10 seconds and after which the second cout will get printed onto the screen.

sleep() for milliseconds

In the 11th version of C++ language, you can do this with standard library facilities:

sleep() function for milliseconds can be implemented as :

std::this_thread::sleep_for(std::chrono::milliseconds(x));

Clear and readable, no more need to guess at what units the sleep() function takes.

Conclusion

In this article, we deep dive into the sleep() function in C++ and explored its functionalities with examples. Now, there are various similar functions like sleep() function in C++ like usleep(), sleep_for(), and sleep_until() which you can explore!

Congratulations on getting this far! Now give yourself a pat on the back. Good job!

Источник

How Do you Add a Timed Delay to a C++ Program

Time delays in C++ are important for several reasons, such as regulating the speed of a program, adding a stop event between the programs, or synchronizing multiple programs. It also useful in case of debugging when a user wants to check whether a certain portion of a code runs successfully or not. With the use of the standard C++ libraries, timed delays can be easily included into a C++ program.

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.

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).

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.

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).

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.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.

Источник

C++ Sleep functions for windows & Linux – Code Example

In this article we will look at few methods to implement C++ Sleep functionality. There are various issues in delaying a thread, process or event. First of all none of the methods are accurate at millisecond precision. Second, they are platform specific and their declarations are different according to windows or linux operating systems.

Code Example

1. Sleep in Windows

In Windows, we can use Sleep() function which accepts number of milliseconds to delay the process. It’s syntax is –

void Sleep( [in] DWORD dwMilliseconds );

You can use windows Sleep in c++ code as –

2. sleep in Linux

Linux provides sleep function which accepts time in seconds.

3. nanosleep in Linux

If you want more higher resolution of delay then you can use nanosleep() function. It accepts time in nanoseconds. The acceptable values are from 0 to 999999999.

#include // . nonosleep(3747384)

4. usleep in Linux

If your requirements are for microseconds, then you can use usleep in Linux. Use it like this –

#include // . usleep(5000000) // 5 seconds

5. Using chrono in C++ 11

If you are using c++ 11 then you can use chrono library along with thread library. It is the latest method of delaying a program execution.

#include #include // . std::this_thread::sleep_for(std::chrono::seconds(5)); // 5s

b. Using chrono::milliseconds –

#include #include // . std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // 5s

c. Using chrono::microseconds –

#include #include // . std::this_thread::sleep_for(std::chrono::microseconds(5000*1000)); // 5s

d. Using chrono::nanoseconds –

#include #include // . std::this_thread::sleep_for(std::chrono::nanoseconds(5000*1000*1000)); // 5s
  • Allocate heap memory to JavaScript in Next.js, Reactjs -…
  • Component not re-rendering on array state change – Code…
  • How to add dividers between list items in React native? Code…
  • Git rename local branch – git branch -m oldname newnm – Code…
  • what utility is equivalent to the pathping command on linux…
  • valueerror could not convert string to float – Code Example
  • How to select multiple items from list in React Native? Code…
  • Docker desktop stopped error solution – Code Example
  • input contains nan, infinity value large for…
  • How to create a transparent StatusBar in React Native? Code…
  • Set & Clear Timeout in React Component on (un)mount – Code…
  • Clear Ubuntu terminal or WSL without clearing history – Code…
  • node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28’…
  • valueerror: too many values to unpack (expected 2) – Code…
  • Commands to delete local & remote git branches – Code…

Источник

Оцените статью