Skip to content

Commit

Permalink
Fixes to the framelimiter to make it more accurate.
Browse files Browse the repository at this point in the history
This change improves the accuracy of the framelimiter so it yields the expected result. Before this change, it was impossible to actually achieve the default maximum framerate of 120 FPS.

Please note that the Windows code does not have a sleep function with a high enough granularity to take advantage of the improved precision, so Windows builds will still have an imprecise FPS cap.
  • Loading branch information
isojalka authored and hifi committed Mar 16, 2024
1 parent f4cc9b0 commit da253d3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
13 changes: 7 additions & 6 deletions common/framelimit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,13 @@ void Frame_Limiter(FrameLimitFlags flags)
#else
auto frame_end = std::chrono::steady_clock::now();
#endif
int64_t _ms_per_tick = 1000 / Settings.Video.FrameLimit;
auto remaining =
_ms_per_tick - std::chrono::duration_cast<std::chrono::milliseconds>(frame_end - frame_start).count();
if (remaining > 0) {
ms_sleep(unsigned(remaining));
unsigned int min_frame_time = 1000000 / Settings.Video.FrameLimit;
auto cur_frame_time = std::chrono::duration_cast<std::chrono::microseconds>(frame_end - frame_start).count();
if (cur_frame_time < min_frame_time) {
frame_start += std::chrono::microseconds{min_frame_time};
us_sleep(min_frame_time - cur_frame_time);
} else {
frame_start = frame_end;
}
frame_start = std::chrono::steady_clock::now();
}
}
15 changes: 15 additions & 0 deletions common/mssleep.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@
#include <time.h>
#endif

/**
* Yield the current thread for at least us microseconds.
*/
static inline void us_sleep(unsigned us)
{
#ifdef _WIN32
Sleep((us + 999) / 1000);
#else
struct timespec ts;
ts.tv_sec = us / 1000000;
ts.tv_nsec = (us % 1000000) * 1000;
nanosleep(&ts, NULL);
#endif
}

/**
* Yield the current thread for at least ms milliseconds.
*/
Expand Down

0 comments on commit da253d3

Please sign in to comment.