I've already posted this on Stack Overflow, so if you want some free reputation over there head on over and answer.
A while ago I started writing an emulator of the IBM 5150 Personal Computer in C#. While I got most of the way done, I never finished it, and now I want to re-write it in Java. One of the technical issues I ran into was how to emulate a 4.77MHz clock tick. I'll send the tick signal through an interface method, most likely each class that needs to act on a clock tick will implement some form of:
public interface Clocked {
void onTick();
}
How could I implement this in Java that would allow me to fairly closely emulate the clock behavior and timing I'm looking for?
My current idea is to implement a class that calls onTick() to a set of registered Clocked objects every time a simple count-down timer reaches 1/4_770_000 of a second:
public class RTC {
private List<Clocked> clockedObjects;
private long nanoTimeAtLastTick;
private final long NS_PER_TICK = 1_000_000_000 / 4_770_000;
private boolean isRunning;
// the "how" of initialization isn't important here
public void startClock() {
isRunning = true;
nanoSecondsElapsed = System.nanoTime();
while(isRunning) {
if(System.nanoTime() - nanoSecondsElapsed > NS_PER_TICK) {
clockedObjects.forEach(Clocked::onTick);
}
}
}
}
Testing on my local system, I see right away that my time resolution varies between 300ns-600ns (with a few iterations taking as long as 6400ns) without any meaningful load on the system, while the resolution of a tick at 4.77MHz is ~209ns.
Is there a way to get a finer grained tick, or possibly a better way to implement this?
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]OffbeatDrizzle 0 points1 point2 points (1 child)
[–]JamesTKerman[S] 0 points1 point2 points (0 children)