Created
October 8, 2023 03:42
-
-
Save hengfeiyang/9dfd78f293797fc793f02aac18163d29 to your computer and use it in GitHub Desktop.
data_table
This file contains 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::{f64::consts::PI, time::Instant}; | |
const N: usize = 1_000_000; | |
const N_WARMUP: usize = 100; | |
#[derive(Copy, Clone)] | |
enum ShapeType { | |
Square, | |
Rectangle, | |
Triangle, | |
Circle, | |
} | |
struct Shape { | |
width: f64, | |
height: f64, | |
shape_type: ShapeType, | |
} | |
static CTABLE: [f64; 4] = [1.0, 1.0, 0.5, PI]; | |
impl Shape { | |
fn area(&self) -> f64 { | |
CTABLE[self.shape_type as usize] * self.width as f64 * self.height as f64 | |
} | |
} | |
fn total_area(shapes: &[Shape]) -> f64 { | |
shapes.iter().fold(0.0, |a, s| a + s.area()) | |
} | |
fn init_shapes() -> Vec<Shape> { | |
let mut shapes: Vec<Shape> = Vec::with_capacity(3 * N as usize); | |
let _: Vec<_> = (0..3 * N) | |
.map(|_| { | |
let mut rng = rand::thread_rng(); | |
match rng.gen_range(0..3) { | |
0 => { | |
shapes.push(Shape { | |
width: 4.0, | |
height: 4.0, | |
shape_type: ShapeType::Square, | |
}); | |
} | |
1 => { | |
shapes.push(Shape { | |
width: 4.0, | |
height: 4.0, | |
shape_type: ShapeType::Rectangle, | |
}); | |
} | |
2 => { | |
shapes.push(Shape { | |
width: 4.0, | |
height: 4.0, | |
shape_type: ShapeType::Triangle, | |
}); | |
} | |
_ => { | |
shapes.push(Shape { | |
width: 4.0, | |
height: 4.0, | |
shape_type: ShapeType::Circle, | |
}); | |
} | |
} | |
}) | |
.collect(); | |
shapes | |
} | |
fn main() { | |
let shapes: Vec<Shape> = init_shapes(); | |
// Running benchmark | |
let start = Instant::now(); | |
let mut total = 0.0; | |
for _ in 0..N_WARMUP { | |
total = total_area(&shapes); | |
} | |
let duration = start.elapsed(); | |
println!("{}. Enum 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