Day 018 - Sleep Assert()?

In the Q&A on day 018, Casey answers a question regarding (testSecondsElapsedForFrame < targetSecondsPerFrame) around 01:12:00. Even though the Visual Studio console shows his program exceeding (at 34-35ms) the target milliseconds per frame (33.33), he doesn't seem to trigger that assert in his program, and I do.

Does sleep somehow exhibit different behavior on different systems? I wouldn't think so, because I was able to set the sleep granularity to 1 ms. Nonetheless, the program with the sleep commented out runs anywhere between 3-7 ms on a given frame on my system. With the sleep(), it's somewhere around 34 ms and triggers the assert (seemingly on the scale of 1/1,000 of a second at times). Is it a underlying bug in the code that he fixes later, or just Windows and hardware interactions?

Update: Just tested using the clean 018 source and the same issue happens, so it's probably unintended behavior.

Edited by echu on
I guess it will be addressed in later episodes (I don't remember).

You can't rely on Sleep to ensure your frames are 33ms. Even if you could make sure they were the right length, you don't know when the frame is presented to the screen and so you don't know when to start counting. Later on the series, Casey will switch to use OpenGL and you'll then be able to properly synchronize your frames. If you don't want to wait and use Windows 7 with the compositor enabled or later version of Windows, you can call DwmFlush to make the program wait for the window compositor to present the frame on the screen. You won't need any Sleep on busy loop any more.
The assert was triggered on my system as well when I wrote that part on my own (which I promptly commented out to keep going). On day 20 Casey changes that part (removing the assert and replacing it with an if and a TODO) while saying that there shouldn't be an assert there but that it should be logged eventually when we miss the sleep. So from the end of day 20, you shouldn't have that issue anymore.

Edited by Rémy Roy on