waiting program
Nov 4, 2014 at 11:09am UTC
this program waits 3 sec. the problem is that it continues to use 100% of one CPU thread. How to wait without using CPU ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// wait zzzzz
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t start = time(NULL);
while (true )
if ( difftime(time(NULL), start) >= 3 )
break ;
cout << "Wall time passed: " << difftime(time(NULL), start) << " second.\n" ;
return 0;
}
Nov 4, 2014 at 11:17am UTC
Nov 4, 2014 at 11:17am UTC
Nov 4, 2014 at 11:20am UTC
Nov 4, 2014 at 11:21am UTC
Modern OS's provide a sleep system call.
And moder C++ provides standard way to do so:
http://en.cppreference.com/w/cpp/thread/sleep_for
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <chrono>
#include <thread>
int main()
{
std::this_thread::sleep_for( std::chrono::seconds(3) );
}
//Or with C++14
#include <chrono>
#include <thread>
using namespace std::literals;
int main()
{
std::this_thread::sleep_for( 3s );
}
Nov 4, 2014 at 12:27pm UTC
thanks for the responses. the code i came to know...
1 2 3 4 5 6 7 8 9 10 11 12
// its deprecated ... runs, but shows warning in gcc 4.8.1
#include <iostream>
//#include <cstdlib>
using namespace std;
int main() {
cout << 5 << endl;
_sleep(5000); // pauses for 5 seconds
cout << 6 << endl;
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13
// sleep_for //C++11
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main() {
cout << 5 << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
cout << 6 << endl;
return 0;
}
Nov 4, 2014 at 1:01pm UTC
i found another example from
http://www.cplusplus.com/forum/beginner/13906/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <windows.h> ///
#include <iostream>
using namespace std;
int main( ){
cout << "5" << endl;
//We use 1000 since Sleep takes the amount of time in milliseconds, and 1000 ms = 1 second
Sleep( 1000 );
cout << "4" << endl;
Sleep( 1000 );
cout << "3" << endl;
Sleep( 1000 );
cout << "2" << endl;
Sleep( 1000 );
cout << "1" << endl;
Sleep( 1000 );
cout << "Congratulations, you've just wasted 5 seconds of your life!" ;
cin.get( );
return 0;
}
it ran without any warning in both visual studio 2012 and in gcc.
Topic archived. No new replies allowed.