Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.