Skip to content

Instantly share code, notes, and snippets.

@nphyx
Last active February 5, 2024 00:45
Show Gist options
  • Save nphyx/e5970f20c1ce761a0a03276810bcefc4 to your computer and use it in GitHub Desktop.
Save nphyx/e5970f20c1ce761a0a03276810bcefc4 to your computer and use it in GitHub Desktop.
Simple FPS Limit in Rust/Vulkano
// I don't know if this is the "right" way to do this, or even a "not stupid" way to do this, but I couldn't
// find an idiomatic approach and I'm a noob at Vulkan and graphics programming in general, so I came up with this
// the only reason it was difficult is that I first had to learn how Rust likes doing timing, using Duration and Instant
// rather than just using a ms/ns timestamp integer as one might expect
fn main() {
// [...] all your vulkan initialization stuff
// this is the target FPS
let fps = 60u32;
// set up a Duration representing the frame interval
let frame_interval = Duration::new(0, 1000000000u32/fps);
// this is stored as an Instant, representing the current time from an arbitrary epoch
let mut frame_start:Instant;
// this is where we'll store the delta (time from beginning of frame to completing it)
let mut frame_delta:Duration;
// these are used to display fps, can omit them if you don't want to do that
let mut frame_count_start = Instant::now();
let mut frame_count = 0f64;
let mut frame_count_elapsed:f64;
// main render loop
loop {
frame_start = Instant::now();
// ...
// all your render loop stuff goes here
// ...
// calculate fps
frame_count = frame_count + 1f64;
frame_count_elapsed = frame_count_start.elapsed().as_secs() as f64 + (frame_count_start.elapsed().subsec_nanos() as f64 / 1000000000f64);
// print fps to stdout
print!("\rFPS: {:.2}", frame_count / frame_count_elapsed);
// go to sleep for remainder of frame_interval
frame_delta = frame_start.elapsed();
if frame_delta < frame_interval {thread::sleep(frame_interval - frame_delta)};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment