how to get fps current game in rust

To get the current FPS (Frames Per Second) in a Rust game, you can use the following approaches:

1. Using the std::time module

You can calculate the FPS by measuring the time difference between two consecutive frames and then dividing the number of frames by the time elapsed.

main.rs
use std::time::{Duration, Instant};

struct Game {
    last_frame_time: Instant,
    frames: u32,
}

impl Game {
    fn new() -> Self {
        Game {
            last_frame_time: Instant::now(),
            frames: 0,
        }
    }

    fn update(&mut self) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.last_frame_time);
        self.frames += 1;

        if elapsed.as_secs() > 0 {
            let fps = self.frames as f64 / elapsed.as_secs_f64();
            println!("FPS: {}", fps);
            self.last_frame_time = now;
            self.frames = 0;
        }
    }
}
614 chars
29 lines

2. Using a library like winit or minifb

If you're using a library like winit or minifb for handling window events and rendering, you can use their built-in functionality to get the FPS.

For example, with winit, you can use the event_loop to get the time elapsed since the last frame and calculate the FPS:

main.rs
use winit::{
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new().build(&event_loop).unwrap();

    let mut last_frame_time = std::time::Instant::now();
    let mut frames = 0;

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
                _ => (),
            },
            Event::MainEventsCleared => {
                let now = std::time::Instant::now();
                let elapsed = now.duration_since(last_frame_time);
                frames += 1;

                if elapsed.as_secs() > 0 {
                    let fps = frames as f64 / elapsed.as_secs_f64();
                    println!("FPS: {}", fps);
                    last_frame_time = now;
                    frames = 0;
                }

                window.request_redraw();
            }
            _ => (),
        }
    });
}
1161 chars
40 lines

3. Using a game engine like amethyst or specs

If you're using a game engine like amethyst or specs, you can use their built-in functionality to get the FPS.

For example, with amethyst, you can use the Application struct to get the FPS:

main.rs
use amethyst::{
    prelude::*,
    core::transform::Transform,
    renderer::{types::DefaultBackend, plugins::RenderFlat2D},
    utils::application_root_dir,
};

struct ExampleState;

impl SimpleState for ExampleState {
    fn update(&mut self, data: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans {
        let fps = data.world.get_resource::<FPSCounter>().unwrap();
        println!("FPS: {}", fps.get_fps());

        Trans::None
    }
}

fn main() -> amethyst::Result<()> {
    let app_root = application_root_dir()?;
    let display_config_path = app_root.join("display.ron");
    let assets_dir = app_root.join("assets");

    let game_data = GameDataBuilder::default()
        .with_bundle(RenderFlat2D::default())?
        .with(FPSCounter::default());

    let mut game = Application::build(assets_dir, ExampleState)?
        .with_resource(game_data)
        .build()?;
    game.run();
    Ok(())
}

struct FPSCounter {
    last_update: std::time::Instant,
    frames: u32,
}

impl Default for FPSCounter {
    fn default() -> Self {
        Self {
            last_update: std::time::Instant::now(),
            frames: 0,
        }
    }
}

impl FPSCounter {
    fn get_fps(&mut self) -> f64 {
        let now = std::time::Instant::now();
        let elapsed = now.duration_since(self.last_update);
        self.frames += 1;

        if elapsed.as_secs() > 0 {
            let fps = self.frames as f64 / elapsed.as_secs_f64();
            self.last_update = now;
            self.frames = 0;
            fps
        } else {
            0.0
        }
    }
}
1578 chars
65 lines

related categories

gistlibby LogSnag