frame_history.rs (1404B)
1 use egui::util::History; 2 3 pub struct FrameHistory { 4 frame_times: History<f32>, 5 } 6 7 impl Default for FrameHistory { 8 fn default() -> Self { 9 let max_age: f32 = 1.0; 10 let max_len = (max_age * 300.0).round() as usize; 11 Self { 12 frame_times: History::new(0..max_len, max_age), 13 } 14 } 15 } 16 17 impl FrameHistory { 18 // Called first 19 pub fn on_new_frame(&mut self, now: f64, previous_frame_time: Option<f32>) { 20 let previous_frame_time = previous_frame_time.unwrap_or_default(); 21 if let Some(latest) = self.frame_times.latest_mut() { 22 *latest = previous_frame_time; // rewrite history now that we know 23 } 24 self.frame_times.add(now, previous_frame_time); // projected 25 } 26 27 #[allow(unused)] 28 pub fn mean_frame_time(&self) -> f32 { 29 self.frame_times.average().unwrap_or_default() 30 } 31 32 #[allow(unused)] 33 pub fn fps(&self) -> f32 { 34 1.0 / self.frame_times.mean_time_interval().unwrap_or_default() 35 } 36 37 pub fn _ui(&mut self, ui: &mut egui::Ui) { 38 ui.label(format!( 39 "Mean CPU usage: {:.2} ms / frame", 40 1e3 * self.mean_frame_time() 41 )) 42 .on_hover_text( 43 "Includes egui layout and tessellation time.\n\ 44 Does not include GPU usage, nor overhead for sending data to GPU.", 45 ); 46 egui::warn_if_debug_build(ui); 47 } 48 }