How to make the program sleep for x milliseconds in C++?


Here we will see how to sleep for x (given by user) milliseconds in C++ program.

To do this thing we can use different libraries. But here we are using the clock() function. The clock() will return the current CPU time. Here we will try to find the ending time from the clock, and the given x value. Then for that amount of time, we will run one blank while loop to take the time. Here one macro is used called CLOCKS_PER_SEC, this finds the number of clock ticks per second.

Let us see the code to get the better idea about the concept.

Example

#include <iostream>
#include <time.h>
using namespace std;
void sleepcp(int milli) {
   // Cross-platform sleep function
   clock_t end_time;
   end_time = clock() + milli * CLOCKS_PER_SEC/1000;
   while (clock() < end_time) {
      //blank loop for waiting
   }
}
int main() {
   cout << "Staring counter for 7 seconds (7000 Milliseconds)" << endl;
   sleepcp(7000);
   cout << "Timer end" << endl;
}

Output

Staring counter for 7 seconds (7000 Milliseconds)
Timer end

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements