0

How to insert sleep/delay in a program?

if I wrote a hello world program how to insert time in it ? Like delay or sleep please help me out in this..!!

30th Oct 2016, 9:02 AM
neil
neil - avatar
2 ответов
0
You can use library called ctime. When you call its function time(NULL), it returns number of seconds from 1. 1. 1970. So your delay program could look like this: #include <ctime> using namespace std; int main() { // Your code before delay // time_t is just data type for storing time, like int, double, string etc time_t actual_time = time(NULL); // time(NULL) in condition is changing every second, while actual_time is not changing, so it lasts 3 seconds while time(NULL) - actual_time > 3. while(time(NULL) - actual_time < 3) ; // This is just empty statement. It says "do nothing" // Your code after delay } If you use windows os, you can #include <Windows.h> and then use function Sleep(number_of_milliseconds), but I don't recommend this, because your code will not work on other operating systems.
30th Oct 2016, 11:01 AM
Daniel Oravec
Daniel Oravec - avatar
0
#include <cstdlib> #include <iostream> int main() { std::cout << "Sleeping for 2 seconds ..." << std::endl; system("sleep 2"); return 0; } As simple.But it has some performance issues http://www.cplusplus.com/articles/j3wTURfi/ Unix has a variety of sleep APIs (sleep, usleep, nanosleep). The only Win32 function I know of for sleep is Sleep(), which is in units of milliseconds. //For unix #include <unistd.h> #include <iostream> int main() { std::cout << "Sleeping for 2 seconds ..." << std::endl; sleep(2); return 0; } //For Windows #include <windows.h> #include <iostream> int main() { std::cout << "Sleeping for 2 seconds ..." << std::endl; Sleep(2);//Note the S(uppercase) return 0; }
30th Oct 2016, 3:39 PM
மனோஜ்குமார் பழனிச்சாமி
மனோஜ்குமார் பழனிச்சாமி - avatar