5

I am trying to make a gameboy emulator, but it plays faster than it should.

This is the timing code I'm using 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 gameboy cpu (4194304).
  • cpu.T is cycles passed until now.
  • PerfCountFrequency is the result of QueryPerformanceFrequency which I called before entering the loop.

When I compare it to another emulator (VBA) which plays at the correct speed, my emulator goes faster. What is the problem here?

8
  • I wouldn't use QueryPerformancCounter(). I've heard that since modern CPU's dynamically alter their speed for power savings, this isn't necessarily always accurate though I don't have a definite source for that. I generally use std::chrono::steady_clock for profiling now as long as its granularity is sufficiently smaller than the periods you are trying to time.
    – RyanP
    Jul 18, 2015 at 19:58
  • Are you counting Gameboy CPU cycles correctly?
    – Ross Ridge
    Jul 18, 2015 at 20:56
  • @RyanP As soon as I include <chrono> I get the message "error count exceeds 100. Stopping compilation. (Using Visual Studio). I'll wait for another solution for now.
    – devil0150
    Jul 18, 2015 at 21:05
  • @RossRidge Yes. I compared the logs with another open source emulator I found which worked correctly.
    – devil0150
    Jul 18, 2015 at 21:05
  • @devil0150 What compiler are you using? <chrono> was introduced in C++11, so older compilers may not have support for it. Alternatively Boost offers a chrono library as well.
    – RyanP
    Jul 18, 2015 at 21:14

1 Answer 1

1

Sleep is the wrong function here. 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 thread may sleep for less than the specified length of time"

DirectX may have a method (VBLANK??), but you could work out minor issues by working out what the next frame time should be, and if the sleep is too small, saving up Sleeps until it gets above the timer resolution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.