JustClaire wrote:
Hello
I have been making an emulator for 6502 for the past week but i am stuck at an issue.
WARNING: this question is not entirely about 6502, but more about emulator design in general.
The CPU emulation code can currently run at ~70-80MHz on average, but i am having trouble controlling the frequency precisely. I want my code to work multiplatform but Afaik windows api does not allow for nanosecond precision timers unlike unix so i cannot set the emulator to run precisely at a few MHz.
It is kind of ironic that the issue is running code slower than its max speed.
What would be the preferred approach to control emulator frequency? I want to be able to at least run it at the max datasheet frequency of 14MHz if its possible
One thing to note is that not all Unixes/Linuxes/BSDs/etc. have nanosecond resolution and sometimes other means have to be employed. And even if you do have seemingly ns timing, you should always check the minimum interval possible - use the clock_getres(2) system call to see what's possible. also check the minimum duration of a system call - especially things like sleep(), nanosleep(), etc. you may well find that they are much longer than you're expecting.
One thing I did for my cycle-accurate PDP-8 emulator a while back was to bypass the kernel and use a hardware timer because the system I was running it on only had a resolution of 1µS and I needed something quicker - that was on a Raspberry Pi Zero and obviously isn't possibly on all platforms. So my strategy was:
- Read the hardware timer (A)
- execute my C code to Interpret the instruction
- Read the hardware timer again and use it to calculate the time left to the next clock tick (cycleTime - (current - A))
- Busy loop for this time, reading/comparing the hardware timer
That works remarkably well and I was able to check my cycle timing against a real PDP-8 and they matched.
Personally, cycle accurate is the way to go because (other than the fun with a PiTubeDirect - 65C02 @ 300Mhz) then if you want faster you might as well use a different CPU IMO ... (although there are scenarios like ...
that obscure bug that only happens once a day where speeding up the emulating might help debug it, etc. but then how did they do it on the old days...)
Cheers,
-Gordon
_________________
--
Gordon Henderson.
See my
Ruby 6502 and 65816 SBC projects here:
https://projects.drogon.net/ruby/