Simplify framerate limit

This commit is contained in:
Kevin Hamacher 2020-02-14 20:08:01 +01:00
parent eb62d59817
commit 28d792e48d

View File

@ -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));
}
}