Why does a game loop need to sleep?

571 views Asked by At

Why does the game loop need to sleep and how do you determine for how long? How do you keep the sleep time of a thread constant?

1

There are 1 answers

0
Peter Bloomfield On

The operating system will usually be running a lot of threads/processes simultaneously on any given core, and the scheduler has to decide how much processor time each one is going to get. If a thread is running continuously (without sleeping), it can end up dominating available processor resources.

Sometimes that's appropriate, e.g. for extremely computationally intensive applications. However, most programs shouldn't need to do that. With games in particular, the bottleneck is often graphics or IO performance, rather than available CPU resources (i.e. your program could end up wasting processor time while it waits for something else to catch up).

Making your thread sleep for a short period on each iteration frees-up some of the processor time. That lets the scheduler allocate time for other threads/processes, and keeps the system generally running better. Essentially, the sleep time is for the benefit of the rest of the system, rather than your own program.

There isn't really a 'correct' amount of sleep time as such. Generally speaking though, your thread should sleep for as long as possible without impacting your program's performance. A good way to do that is to determine the desired framerate for your game, and from there calculate how much of a delay you can afford between each frame.

Every time round your main loop, check if that amount of time has elapsed since the previous frame. If not, sleep for a short period, and try again next time round the loop.