From 1504e70146f5d93bd01384b9ca09f37bb1c701ef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Magalh=C3=A3es?= <joamag@gmail.com>
Date: Sun, 4 Jun 2023 19:31:14 +0100
Subject: [PATCH] chore: support for chunk size for clock_m usage

---
 frontends/sdl/src/main.rs | 18 +++++++++++++-----
 src/gb.rs                 |  8 +++++++-
 2 files changed, 20 insertions(+), 6 deletions(-)

diff --git a/frontends/sdl/src/main.rs b/frontends/sdl/src/main.rs
index 5ab6c7fc..b9ac2e86 100644
--- a/frontends/sdl/src/main.rs
+++ b/frontends/sdl/src/main.rs
@@ -39,17 +39,18 @@ const VOLUME: f32 = 64.0;
 
 pub struct Benchmark {
     count: usize,
+    chunk_size: Option<usize>,
 }
 
 impl Benchmark {
-    pub fn new(count: usize) -> Self {
-        Self { count }
+    pub fn new(count: usize, chunk_size: Option<usize>) -> Self {
+        Self { count, chunk_size }
     }
 }
 
 impl Default for Benchmark {
     fn default() -> Self {
-        Self::new(50000000)
+        Self::new(50000000, None)
     }
 }
 
@@ -224,12 +225,19 @@ impl Emulator {
         println!("Going to run benchmark...");
 
         let count = params.count;
+        let chunk_size = params.chunk_size.unwrap_or(1);
         let mut cycles = 0;
 
         let initial = SystemTime::now();
 
-        for _ in 0..count {
-            cycles += self.system.clock() as u32;
+        if chunk_size > 1 {
+            for _ in 0..(count / chunk_size) {
+                cycles += self.system.clock_m(chunk_size) as u32;
+            }
+        } else {
+            for _ in 0..count {
+                cycles += self.system.clock() as u32;
+            }
         }
 
         let delta = initial.elapsed().unwrap().as_millis() as f32 / 1000.0;
diff --git a/src/gb.rs b/src/gb.rs
index a43b6b11..c6b0cd43 100644
--- a/src/gb.rs
+++ b/src/gb.rs
@@ -412,10 +412,16 @@ impl GameBoy {
         cycles
     }
 
+    /// Risky function that will clock the CPU multiple times
+    /// allowing an undefined number of cycles to be executed
+    /// in the other Game Boy components.
+    /// This can cause unwanted behaviour in components like
+    /// the PPU where only one mode switch operation is expected
+    /// per each clock call.
     pub fn clock_m(&mut self, count: usize) -> u16 {
         let mut cycles = 0u16;
         for _ in 0..count {
-            cycles += self.clock() as u16;
+            cycles += self.cpu_clock() as u16;
         }
         let cycles_n = cycles / self.multiplier() as u16;
         if self.ppu_enabled {
-- 
GitLab