In the DMG-01 emulation, time is measured in CPU cycles rather than nanoseconds. Each instruction takes a specific number of cycles to complete. To synchronize the system, the execute method must return both the next Program Counter (pc) value and the number of cycles consumed by the instruction.
For example, an ADD instruction targeting register C takes 4 cycles. The Game Boy's clock speed is 4.19 MHz (4,190,000 cycles per second).
impl CPU {
fn execute(&mut self, instruction: Instruction) -> (u16, u8) {
match instruction {
Instruction::ADD(target) => {
match target {
ArithmeticTarget::C => {
// Returns (next_pc, cycles_consumed)
(self.pc.wrapping_add(1), 4)
}
_ => { panic!("TODO: support more targets") }
}
}
_ => { panic!("TODO: support more instructions") }
}
}
}