I am building a simple 2D game in Rust using Piston. I used the examples from the Piston documentation and expanded it, and it works quite well. However, I get pretty poor performance:
- Drawing just 2 squares gives me a frame rate of about 30-40 FPS
- Figure 5,000 squares gives me a frame rate of around 5 FPS
This is on Core i7 @ 2.2GHz running Windows 10. Rust version 1.8, Piston version 0.19.0.
Is this expected, or have I made any mistakes in my code? Did I even measure FPS correctly?
extern crate piston_window;
extern crate piston;
extern crate rand;
use piston_window::*;
use rand::Rng;
fn main() {
const SIZE: [u32; 2] = [600,600];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const NUM: u32 = 1000;
const SQUARESIZE: f64 = 10.0;
let window: PistonWindow = WindowSettings::new("test",SIZE)
.exit_on_esc(true)
.build()
.unwrap();
let mut frames = 0;
let mut passed = 0.0;
let mut rng = rand::thread_rng();
for e in window {
if let Some(_) = e.render_args() {
e.draw_2d(|c, g| {
clear(GREEN, g);
for i in 0..NUM {
let x = (i % SIZE[0]) as f64;
let y = (i % SIZE[1]) as f64;
let fill = (x / (SIZE[0] as f64)) as f32;
let color: [f32; 4] = [fill,1.0-fill,fill,fill];
let x = rng.gen_range::<f64>(0.0,SIZE[0] as f64);
//draw the square
let square = rectangle::square(0.0, 0.0, SQUARESIZE);
let transform = c.transform.trans(x-SQUARESIZE/2.0,y-SQUARESIZE/2.0);
rectangle(color, square, transform, g);
}
frames+=1;
});
}
if let Some(u) = e.update_args() {
passed += u.dt;
if passed > 1.0 {
let fps = (frames as f64) / passed;
println!("FPS: {}",fps);
frames = 0;
passed = 0.0;
}
}
}
}
Thank you for your help.
EDIT: taskmgr tells me that it only uses about 17K of memory, but one of my physical processor cores is highlighted when the FPS drops below 20.
EDIT 2: changed the code to a full working example.