Sign in to follow this  

Accurate Timer

This topic is 4279 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Morpheus011
check out GetTickCount()

timeGetTime() == GetTickCount()

Share this post


Link to post
Share on other sites
>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' :)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by JohnBSmall
Quote:
Original post by Anonymous Poster
Quote:
Original post by Morpheus011
check out GetTickCount()

timeGetTime() == GetTickCount()

No, not really.

John B


Yes really.

MSDN:
"timeGetTime" - "This function retrieves the system time, in milliseconds. The system time is the time elapsed since the system started."

"GetTickCount" - "Retrieves the number of milliseconds that have elapsed since the system was started."

Share this post


Link to post
Share on other sites

This topic is 4279 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this