- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements