waiting program

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;
}
Your code isn't suspending the current thread from processing, it's just iterating through the while(...) condition until the if(...) condition becomes true and exits the while via the break. I think what you are looking for is the Sleep() function.

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SLEEP);k(DevLang-%22C%2B%2B%22)&rd=true
I think you can use

std::this_thread::sleep_for

e.g.:

http://www.cplusplus.com/reference/thread/this_thread/sleep_for/

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 );
}
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;
}
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.