Skip to main content
gamedev.net
🔒 Locked

Accurate Timer

Started by TEUTON 10 replies 700+ views
Original Post
TEUTON
TEUTON
I wanted a timer for 20 seconds I wrote this code but it eats up lot of my CPU time...any other efficient way to handle this on windows.

#include <iostream> 
#include <ctime> 

using std::cout;
using std::endl; 
int main() 
{ 
        clock_t start = clock(); 

        while(clock() < (CLOCKS_PER_SEC * 20) + start) 
        { 
                //Code 
        } 
        cout << "Time's up." << endl; 
return 0;
}


DaBono
DaBono
#include <windows.h>int main(){   Sleep( 20000 );   cout << "Time's up" << endl;}
bubu LV
bubu LV
#include <windows.h.>...Sleep(20*1000); // in miliseconds...

TEUTON
TEUTON
Yup. That worked nicely
Thank You
discman1028
discman1028
If you wanted to wait that long, while doing something else useful in the meantime, you could use one of the system time querying functions, and wait until the difference becomes 20 secs. timeGetTime() seems to be the easiest to use.
--== discman1028 ==--
Evil Steve
Evil Steve
Also note that if you want it to be accurate, Sleep() is not the way to go, since it'll sleep for at least the time specified. So if you pass in 20000ms, it may end up waiting for 20500ms or something.

If it's not needed to be too accurate then it's not a problem though.
kloffy
kloffy
To make the list complete, I'll throw in QueryPerformanceCounter().

I think, now we've covered all popular options.
Kitt3n
Kitt3n
>So if you pass in 20000ms, it may end up waiting for 20500ms or something.
Last time I cheched it - on my machine - it was acurate to around 1ms (win2k)

>I think, now we've covered all popular options.
You forgot the good old 'rdtsc' :)
visit my website at www.kalmiya.com
intransigent-seal
intransigent-seal
Quote:
Original post by Anonymous Poster
Quote:
Original post by Morpheus011
check out GetTickCount()

timeGetTime() == GetTickCount()

No, not really.

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.