Skip to content

Instantly share code, notes, and snippets.

@AmineDiro
Last active October 8, 2023 22:28
Show Gist options
  • Select an option

  • Save AmineDiro/9760af54812005f228181cea5b8d3d46 to your computer and use it in GitHub Desktop.

Select an option

Save AmineDiro/9760af54812005f228181cea5b8d3d46 to your computer and use it in GitHub Desktop.
use std::time::Instant;
use rand::Rng;
const N_WARMUP: usize = 100;
static SHAPES_COEFF: [f32; 3] = [1.0, 1.0, 0.5];
const N: usize = 1_000_000;
#[derive(Clone, Copy)]
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)| {
sum + SHAPES_COEFF[*t as usize] * w * h
})
}
}
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();
// Running benchmark
let start = Instant::now();
let mut total = 0.0;
for _ in 0..N_WARMUP {
total = shapes.total_area();
}
let duration = start.elapsed();
println!(
"{}. Data_oriented + Table . 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