Sign in to follow this  
fathom88

Question About Wait/Sleep On Windows

Recommended Posts

I placed a timer inside my loop using GetTickCount() for VC++. I also placed a sleep for 1 millisecond. I found the timer would give me a passage of 0 millisecond or 16 millisecond. I've tried replacing the Sleep with a WaitForSingleObject and a wait time of 1 milli. Why does this happen? It it not constant. Sometimes, it runs with 0; sometimes, 16. Does it have anything to do with thread priority?

Share this post


Link to post
Share on other sites
GetTickCount() doesn't have 1 ms resolution. If you want an accurate reading of how much time has passed, you'll need to use a different method of reading the time. IIRC, both QueryPerformanceCounter() and timeGetTime() should give you more accurate results.

Share this post


Link to post
Share on other sites
Also, most commands that wait (such as Sleep) don't run at millisecond resolution either. You'll probably be scheduled to run no quicker than every 10 milliseconds, unless you want to dig deeply into how the scheduling on Windows works.

Share this post


Link to post
Share on other sites
Did you try and use SetPriorityClass to set it to REALTIME_PRIORITY_CLASS? It could give you better results, but Windows isn't really a real-time OS.

Share this post


Link to post
Share on other sites
A) Your timer code cannot accurately time something as smaller as 1ms.

B) Sleep takes a suggested number of milliseconds to put aside your process. The actual number of ms your program gives up is decided by the systems task scheduler - if there is another high priority thread, the sleep could be much longer then you expected. Take the sleep time parameter as the minimum amount of time your program would like to give up.

Share this post


Link to post
Share on other sites
Quote:
Original post by krum
Did you try and use SetPriorityClass to set it to REALTIME_PRIORITY_CLASS? It could give you better results, but Windows isn't really a real-time OS.


Be careful when you do that. If your app is in realtime priority and it takes too long to run, or doesn't free up resources properly, or in some other way misbehaves (perhaps while being debugged), it can cause the windows scheduler to lock up the system, or drop the system speed to a crawl.

Share this post


Link to post
Share on other sites

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