fps counter in rust

To create an FPS counter in Rust, you can use the following code:

main.rs
use std::time::Instant;

struct FpsCounter {
    last_frame_time: Instant,
    frames: u32,
    fps: u32,
}

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

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

        if elapsed.as_secs() >= 1 {
            self.fps = self.frames;
            self.frames = 0;
        }
    }

    fn get_fps(&self) -> u32 {
        self.fps
    }
}

fn main() {
    let mut fps_counter = FpsCounter::new();

    loop {
        // Your game loop logic here
        // ...

        fps_counter.update();
        println!("FPS: {}", fps_counter.get_fps());
    }
}
851 chars
46 lines

This code creates a simple FpsCounter struct that tracks the time elapsed since the last frame and the number of frames rendered. The update method is called every frame to update the FPS counter, and the get_fps method returns the current FPS value.

Note: This code uses the std::time::Instant type to measure time, which provides high-resolution timing. The as_secs method is used to check if one second has elapsed since the last frame.

Also, this code does not account for the actual rendering time, it just counts the number of frames rendered in the last second. For a more accurate FPS counter, you would need to measure the time it takes to render each frame.

Example use cases:

  • In a game loop, call fps_counter.update() at the start of each frame to update the FPS counter.
  • Use fps_counter.get_fps() to display the current FPS value in your game's UI.

Remember to handle any errors that may occur during the execution of the code.

Add error handling code as necessary.

In a real-world application, you would likely want to use a more sophisticated timing library, such as the chrono crate, which provides more advanced timing functionality.

To use the chrono crate, add the following dependency to your Cargo.toml file:

[dependencies]
chrono = "0.4.19"
33 chars
3 lines

Then, use the chrono crate in your code:

main.rs
use chrono::prelude::*;

// ...
32 chars
4 lines

related categories

gistlibby LogSnag