diff --git a/src/cpu.rs b/src/cpu.rs index dc42050..b233ad9 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -893,37 +893,18 @@ impl CPU { #[allow(unused_variables)] pub fn run(&mut self) { - let mut running_sum: i32 = 0; - const INSTRUCTIONS_PER_ROUND: usize = 500; - + let start = Instant::now(); + let mut cycles_executed = 0u128; loop { - let start = Instant::now(); - let mut cycles_executed: usize = 0; - for _ in 0..INSTRUCTIONS_PER_ROUND { - cycles_executed += self.run_instruction() as usize; - } - - // Time that the gameboy would have required to execute the - // instructions above. - // + // Calculate the amount of cycles we should've executed by now. // The gameboy has a freq of 4.194304MHz // This means it takes it 238.418569ns to execute a single // cycle. - let gb_dur = cycles_executed as i32 * 238; - let our_dur = start.elapsed().subsec_nanos() as i32; - let delta = gb_dur - our_dur; - - let full_cycles: i32 = delta / 238; - running_sum += full_cycles; - if full_cycles > 0 { - // println!("[+] [{}] {} cycles, gb: {}, we: {}", running_sum, cycles_executed, gb_dur, our_dur); - sleep(Duration::new(0, (full_cycles - 10) as u32 * 238 as u32)); - } else { - println!( - "[-] [{}] {} cycles, gb: {}, we: {}", - running_sum, cycles_executed, gb_dur, our_dur - ); + let expected_cycles = start.elapsed().as_nanos() / 238; + while cycles_executed < expected_cycles { + cycles_executed += self.run_instruction() as u128; } + sleep(Duration::new(0, 10 * 238)); } }