I'm new to Rust and used the sdl2 crate to visualize 2d spatial simulations.
I found some strange performance issue, which seems to be related to the function texture.update(). Running the toy code below, it takes about 16 seconds to visualize 5000 iterations in a 1600x800 window. Running comparable code in C, Go, or Julia takes only about 6 seconds. I have no idea where this performance regression comes from. But maybe I am doing something wrong? Or is there a reason that Rust is two times slower here than other languages?
Secondly, is this the idiomatic way for using SDL in Rust to performantly visualize 2d simulations? The idea would be to use a function like get_pixels (in the toy code commented out) to safe the simulation results in each simulation step in a Vector and then use texture_update() to update the texture with the new data.
use sdl2::{
pixels::PixelFormatEnum,
rect::Rect,
};
const NX:u32 = 1600;
const NY:u32 = 800;
fn get_pixels(pixels:&mut Vec<u8>) {
for y in 0 .. NY {
for x in 0 .. NX {
let i = (y*3*NX + x*3) as usize;
// put-in some interesting patterns
pixels[i] = 0x00_u8; // here: make the whole window green
pixels[i+1] = 0xff_u8;
pixels[i+2] = 0x00_u8;
}
}
}
fn main() {
let mut pixels: Vec<u8> = vec![0; (NX*NY*3) as usize];
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem
.window("Rust SDL Bench", NX, NY).build().unwrap();
let mut canvas = window.into_canvas().build().unwrap();
let texture_creator = canvas.texture_creator();
let mut texture = texture_creator
.create_texture_streaming(PixelFormatEnum::RGB24, NX, NY).unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
let rect = Rect::new(0,0, NX, NY);
let mut iter = 0;
'running: loop {
iter += 1;
canvas.clear();
//get_pixels(&mut pixels);
texture.update(rect, &pixels, (3*NX) as usize).unwrap();
canvas.copy(&texture, None, Some(rect)).unwrap();
canvas.present();
for _ in event_pump.poll_iter() {}
if iter == 5000 {
break 'running
};
}
}