Register
Handmade Hero»Forums»Code»Day 018 - Sleep Assert()?
10 posts
Day 018 - Sleep Assert()?
1 week, 3 days ago Edited by echu on Nov. 30, 2019, 10 a.m.
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.
Simon Anciaux
692 posts
Day 018 - Sleep Assert()?
1 week, 3 days ago
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.