Gameboy emulator is faster than expected

I am trying to create a gameboy emulator, but it works faster than necessary.

This is the synchronization code that I use in the main loop.

if (cpu.T >= CLOCKSPEED / 40) // if more than 1/40th of cycles passed { // Get milliseconds passed QueryPerformanceCounter(&EndCounter); unsigned long long counter = EndCounter.QuadPart - LastCounter.QuadPart; MSperFrame = 1000.0f * ((double)counter / (double)PerfCountFrequency); LastCounter = EndCounter; // if 1/40th of a second hasn't passed, wait until it passes if (MSperFrame < 25) Sleep(25 - MSperFrame); MSperFrame = 0; cpu.T -= CLOCKSPEED / 40; } 
  • CLOCKSPEED is the cycles per second of the game processor (4194304).
  • cpu.T are the loops going through so far.
  • PerfCountFrequency is the result of a QueryPerformanceFrequency that I called before entering the loop.

When I compare it with another emulator (VBA) that plays at the right speed, my emulator goes faster. What is the problem?

+5
source share
1 answer

Sleeping here is a wrong function. From https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx it mentions that "if dwMilliseconds is less than the resolution of the system clock, the stream may sleep less than a given length time"

DirectX may have a method (VBLANK ??), but you could solve minor problems by developing what should be in the next frame, and if sleep is too small, saving up to Sleeps until it reaches timer resolution.

+1
source

All Articles