Strange sleep behavior between systems

I have a program that uses the Sleep Win32 API call so that the thread hangs for a certain amount of time.
In short, it simulates a camera by sending images previously loaded into memory. I use Sleep to simulate frame rates - Sleep(1000 / fps)

This works fine on my development system (Intel i5 (1st gen), Win7 64), but when I run it on another system (Intel i7-2600 - SandyBridge), the sleep time is completely different and inaccurate.

For example, Sleep(16) sleeps around 32ms
Sleep(3) sleeps for 16ms

In the past, I thought the minimum sleep time on Windows is 15ms , but I do not get this restriction on my dev system.

Any ideas?

Also, is there a better way to achieve the frame rate of my simulator?

+7
source share
2 answers

The sleep function ensures that you will sleep at least for the amount indicated in the call. This causes the thread to pause, allowing switches to other threads (controlled by thread priorities) at the scheduler's leisure. In other words, the sleep thread cannot start immediately after the specified time has elapsed , so you should avoid using sleep for the exact time in the general case.

However, there are ways to get more accurate sleep on Windows. You can call timeGetDevCaps to determine the minimum supported timer resolution, and then call timeBeginPeriod early in the application to set the minimum timer resolution. Be sure to call timeEndPeriod before the application exits.

See the sleep function on MSDN for more information.

+7
source

Instead of relying on explicit sleep behavior or timer-specific platform-specific functions (which may work well, I don't know), you could structure this as a game loop.

Inside the loop, you call a function to give you the current time. You will find out how much has passed since you drew the last frame, and decide when you need to make the next frame at the right time. During development, you should measure the actual number of frames per second and display it.

With this approach, tt is easier to make your cross-platform code more accurate. In addition, your loop manages rather than structuring your code as timer callbacks, which you might also prefer.

The disadvantage is that the β€œwait waiting” cycle means that your process will use the processor all the time unnecessarily. To reduce this, you can bring the processor into your loop by explicitly reassigning the user interface events or, possibly, using a shorter sleep :-).

If you want to learn more about this approach, start a search on materials in game cycles.

Here are some important links:

http://www.koonsolo.com/news/dewitters-gameloop/

http://gafferongames.com/game-physics/fix-your-timestep/

And a discussion of SO:

https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step

+1
source

All Articles