Hello, I've written a timer class in C++ but it's not working properly. The trouble I'm having is that after a couple of minutes the animation becomes choppy. It sometimes fixes automatically after about 5 ~ 60 seconds.
#include <windows.h>
class Timer {
int sleep_length_ms;
double ratio;
LONGLONG duration, next_mark;
LARGE_INTEGER counter, frequency;
public:
Timer(int frame_rate) {
QueryPerformanceCounter(&counter);
QueryPerformanceFrequency(&frequency);
duration = frequency.QuadPart / frame_rate;
next_mark = counter.QuadPart + duration;
ratio = 1000.0 / frequency.QuadPart;
}
bool wait() {
QueryPerformanceCounter(&counter);
sleep_length_ms = (int) (ratio * (next_mark - counter.QuadPart));
if(sleep_length_ms > 0) {
Sleep(sleep_length_ms);
next_mark += duration;
} else {
// if running behind
QueryPerformanceCounter(&counter);
next_mark = counter.QuadPart + duration;
}
return true;
}
};
This is how the class if used in a game loop:
Timer timer(60);
while(run_game) {
update_game();
render_game();
timer.wait();
}
I'm testing this class using a simple Allegro program where a circle bounces off the edges. I tried using the timer class provided by Allegro and the issue resolves so I'm quite sure that the problem lies within my timer class. I can't seem to figure out what I'm doing wrong and would be very grateful if someone can have a read through the code. Thank you!