I'm trying to implement high resolution timing for a Game Boy emulator. A 16-17 millisecond timer is sufficient to get the emulation at roughly the right speed, but it eventually loses sync with precision emulations like BGB.
I originally used QElapsedTimer in a while loop. This gave the expected results and kept sync with BGB, but it feels really sloppy and eats up as much CPU time as it possibly can because of the constantly-running while loop. It also keeps the program resident in Task Manager after closing. I tried implementing it using a one millisecond QTimer that tests the QElapsedTimer before executing the next frame. Despite the reduced resolution, I figured that the timing would average out to the correct speed due to checking the QElapsedTimer. This is what I currently have:
void Platform::start() {
nanoSecondsPerFrame = 1000000000 / system->getRefreshRate();
speedRegulationTimer->start();
emulationUpdateTimer->start(1);
}
void Platform::executionLoop() {
qint64 timeDelay;
if (frameLocked == true)
timeDelay = nanoSecondsPerFrame;
else
timeDelay = 0;
if (speedRegulationTimer->nsecsElapsed() >= timeDelay) {
speedRegulationTimer->restart();
// Execute the cycles of the emulated system for one frame.
system->setControllerInputs(buttonInputs);
system->executeCycles();
if (system->getIsRunning() == false) {
this->stop();
errorMessage = QString::fromStdString(system->getSystemError());
}
//timeDelay = speedRegulationTimer->nsecsElapsed();
FPS++;
}
}
nanoSecondsPerFrame calculates to 16742005 for the 59.73 Hz refresh rate. speedRegulationTimer is the QElapsedTimer. emulationUpdateTimer is a QTimer set to Qt:PreciseTimer and is connected to executionLoop. The emulation does run, but at about 50-51 FPS instead of the expected 59-60 FPS. This is definitely due to the timing because running it without timing restraints results in an exponentially higher frame rate. Either there's an obvious oversight in my code or the timers aren't working like I expect. If anyone sees an obvious problem or could offer some advice on this, I'd appreciate it.