Making an accurate Sleep() function

submited by
Style Pass
2022-06-23 07:00:08

There are many cases in programming where I wish the system Sleep() function was more accurate. Real-time rendering immediately comes to mind, as do animated GUI’s. In both of these cases you want some piece of code to run on a fixed timer, executing precisely every 16.67 milliseconds for 60 FPS.

I haven’t really found any usefull posts or tutorials about how to do precise timing anywhere else, so I decided to make a short post about my own precise timing solution.

Note this is only usefull if you can’t use vsync for synchronization, or if you have no way to guarantee that vsync will be turned on on the user’s machine.

Also note this is by no means a perfect solution, even though it seems to be pretty accurate, it isn’t very robust and might act differently on different systems.

I should also clarify that by “sleep”, I mean the Sleep() system call. It’s a function that makes the calling thread do nothing for a given period of time. In C++ we can use this_thread::sleep_for() from <thread> as a cross-platform way to sleep.

Leave a Comment