Open In App

How to Use usleep Function in C++ Programs?

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Halting the program’s execution at the desired time for a specific duration is one of the most used features in a programming language. This is generally done to provide some time for input or multithreading. This article will teach you how to use the usleep function to halt the program execution in C++.

usleep Function

The usleep function is present in the unistd.h header file is used to suspend the program’s execution for a certain period. The function takes in argument the time in microseconds for which the program execution would suspend and returns a status code. The function syntax is as follows:

int usleep(useconds_t useconds);

Where, 

useconds => Number of microseconds for which the execution is suspended

The function returns the value 0 if the execution was successful (execution successfully suspended) else returns -1.

Suspending execution using the usleep function

Example:

C++




#include <iostream>
#include <unistd.h>
using namespace std;
  
int main()
{
  // Displaying a Statement
  cout << "1st Line" << endl;
    
  // Halting the execution for 10000000 Microseconds (10 seconds)
  usleep(10000000);
    
  // Displaying the line after waiting for 10 seconds
  cout << "2nd Line" << endl;
  return 0;
}


Output:

 

After 10 seconds

 

Explanation: Firstly a string is displayed on the console. Then the usleep function is called with the argument 10000000. Where 10000000 is the time in microseconds which equates to 10 seconds. Hence, the function suspends program execution for 10 seconds once it is called. After which, another line is displayed (after 10 seconds). 

* The effect could be verified at the end when the program execution time is displayed by the Dev C++ compiler, which is 10.06 seconds, whereas a trivial program like this (without the usleep function call) would execute in under 1 second. This could be used to verify the functionality of the program.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads