Last active
October 10, 2023 13:21
-
-
Save AmineDiro/51574a39c866e878b977b4ecdbf03d21 to your computer and use it in GitHub Desktop.
cleancode rust data oriented
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use rand::Rng; | |
| use std::time::Instant; | |
| const N: usize = 1_000_000; | |
| const N_WARMUP: usize = 100; | |
| enum Type { | |
| Rectangle, | |
| Square, | |
| Triangle, | |
| } | |
| struct Shapes { | |
| types: Vec<Type>, | |
| widths: Vec<f32>, | |
| heights: Vec<f32>, | |
| } | |
| impl Shapes { | |
| fn total_area(&self) -> f32 { | |
| self.types | |
| .iter() | |
| .zip(&self.widths) | |
| .zip(&self.heights) | |
| .fold(0.0, |sum, ((t, w), h)| { | |
| let a = { | |
| match t { | |
| Type::Rectangle => w * h, | |
| Type::Square => w * w, | |
| Type::Triangle => 0.5 * w * h, | |
| } | |
| }; | |
| sum + a | |
| }) | |
| } | |
| } | |
| fn init_shapes() -> Shapes { | |
| let mut types: Vec<Type> = Vec::with_capacity(3 * N as usize); | |
| let mut rng = rand::thread_rng(); | |
| for _ in 0..3 * N { | |
| match rng.gen_range(0..3) { | |
| 0 => { | |
| types.push(Type::Rectangle); | |
| } | |
| 1 => { | |
| types.push(Type::Triangle); | |
| } | |
| _ => { | |
| types.push(Type::Square); | |
| } | |
| } | |
| } | |
| Shapes { | |
| types, | |
| widths: vec![4.0].repeat(3 * N), | |
| heights: vec![4.0].repeat(3 * N), | |
| } | |
| } | |
| fn main() { | |
| let shapes = init_shapes(); | |
| let mut total = 0.0; | |
| let start = Instant::now(); | |
| for _ in 0..N_WARMUP { | |
| total = shapes.total_area(); | |
| } | |
| let duration = start.elapsed(); | |
| println!( | |
| "{}. Data oriented took {:?}.", | |
| total, | |
| duration / N_WARMUP as u32 | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment