Last active
October 10, 2023 13:20
-
-
Save AmineDiro/0d4d4c75f6bf7ee5b3020f787d6410f1 to your computer and use it in GitHub Desktop.
cleancode rust dynamic
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; | |
| trait Shape { | |
| fn area(&self) -> f32; | |
| } | |
| #[derive(Clone, Copy)] | |
| struct Square { | |
| side: f32, | |
| } | |
| impl Shape for Square { | |
| fn area(&self) -> f32 { | |
| self.side * self.side | |
| } | |
| } | |
| #[derive(Clone, Copy)] | |
| struct Rectangle { | |
| width: f32, | |
| height: f32, | |
| } | |
| impl Shape for Rectangle { | |
| fn area(&self) -> f32 { | |
| self.width * self.height | |
| } | |
| } | |
| #[derive(Clone, Copy)] | |
| struct Triangle { | |
| base: f32, | |
| height: f32, | |
| } | |
| impl Shape for Triangle { | |
| fn area(&self) -> f32 { | |
| 0.5 * self.base * self.height | |
| } | |
| } | |
| fn total_area(shapes: &[Box<dyn Shape>]) -> f32 { | |
| shapes.iter().fold(0.0, |a, s| a + s.area()) | |
| } | |
| fn init_shape() -> Vec<Box<dyn Shape>> { | |
| let mut shapes: Vec<Box<dyn Shape>> = 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 => { | |
| shapes.push(Box::new(Rectangle { | |
| width: 4.0, | |
| height: 4.0, | |
| })); | |
| } | |
| 1 => { | |
| shapes.push(Box::new(Triangle { | |
| base: 4.0, | |
| height: 4.0, | |
| })); | |
| } | |
| _ => { | |
| shapes.push(Box::new(Square { side: 4.0 })); | |
| } | |
| } | |
| } | |
| shapes | |
| } | |
| fn main() { | |
| let shapes = init_shape(); | |
| let start = Instant::now(); | |
| let mut total = 0.0; | |
| for _ in 0..N_WARMUP { | |
| total = total_area(&shapes); | |
| } | |
| let duration = start.elapsed(); | |
| println!("{}. Dyn 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