summaryrefslogtreecommitdiff
path: root/src/video/sdl2_v.cpp
diff options
context:
space:
mode:
authorPatric Stout <truebrain@openttd.org>2021-02-17 15:19:33 +0100
committerPatric Stout <github@truebrain.nl>2021-02-19 10:43:15 +0100
commiteb9b1ad68d84ddbebb3d9e50f3ec8d3ad195c75c (patch)
tree93a26d1a0681b85653a6b115a4931a240eed34e7 /src/video/sdl2_v.cpp
parentae7a2b9f02b4becdcc7cb96f79031c840198989f (diff)
downloadopenttd-eb9b1ad68d84ddbebb3d9e50f3ec8d3ad195c75c.tar.xz
Change: sleep till the next tick in the main loop
Sleep for 1ms (which is always (a lot) more than 1ms) is just randomly guessing and hoping you hit your deadline, give or take. But given we can calculate when our next frame is happening, we can just sleep for that exact amount. As these values are often a bit larger, it is also more likely the OS can schedule us back in close to our requested target. This means it is more likely we hit our deadlines, which makes the FPS a lot more stable.
Diffstat (limited to 'src/video/sdl2_v.cpp')
-rw-r--r--src/video/sdl2_v.cpp13
1 files changed, 10 insertions, 3 deletions
diff --git a/src/video/sdl2_v.cpp b/src/video/sdl2_v.cpp
index a8d8fc3e1..7c04b8743 100644
--- a/src/video/sdl2_v.cpp
+++ b/src/video/sdl2_v.cpp
@@ -824,10 +824,17 @@ void VideoDriver_SDL::LoopOnce()
/* Emscripten is running an event-based mainloop; there is already some
* downtime between each iteration, so no need to sleep. */
#ifndef __EMSCRIPTEN__
+ /* If we are not in fast-forward, create some time between calls to ease up CPU usage. */
if (!_fast_forward || _pause_mode) {
- if (_draw_mutex != nullptr) draw_lock.unlock();
- CSleep(1);
- if (_draw_mutex != nullptr) draw_lock.lock();
+ /* See how much time there is till we have to process the next event, and try to hit that as close as possible. */
+ auto next_tick = std::min(next_draw_tick, next_game_tick);
+ auto now = std::chrono::steady_clock::now();
+
+ if (next_tick > now) {
+ if (_draw_mutex != nullptr) draw_lock.unlock();
+ std::this_thread::sleep_for(next_tick - now);
+ if (_draw_mutex != nullptr) draw_lock.lock();
+ }
}
#endif
}