Last active
January 27, 2018 09:56
-
-
Save alin23/0d8a612bc2113454b51d6a090867c5d8 to your computer and use it in GitHub Desktop.
Benchmark gauss sum volume
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
#![feature(test)] | |
extern crate test; | |
fn gauss_sum(sequence_size: u16, first_element: u16, increment: u16) -> u16 { | |
if sequence_size == 0 { | |
return first_element; | |
} | |
let last_element = first_element + increment * (sequence_size - 1); | |
sequence_size * (first_element + last_element) / 2 | |
} | |
fn compute_volume_using_gauss_formula( | |
volume: u16, | |
increment_low: u16, | |
increment_high: u16, | |
high_threshold: u16, | |
) -> u16 { | |
if volume <= high_threshold { | |
gauss_sum(volume, 0, increment_low) | |
} else { | |
let first_element = increment_low * (high_threshold - 1) + increment_high; | |
gauss_sum(high_threshold, 0, increment_low) | |
+ gauss_sum(volume - high_threshold, first_element, increment_high) | |
} | |
} | |
fn compute_volume_using_gauss_loop( | |
volume: u16, | |
increment_low: u16, | |
increment_high: u16, | |
high_threshold: u16, | |
) -> u16 { | |
let mut incr = 0; | |
let mut new_volume = 0; | |
for i in 0..volume { | |
new_volume += incr; | |
incr += increment_low; | |
if i > high_threshold { | |
incr += increment_high - increment_low; | |
} | |
} | |
new_volume | |
} | |
fn compute_volume_using_scale_factor(volume: u16, factor: f32) -> u16 { | |
let normalized_volume = volume as f32 / 100.0; | |
let new_volume = normalized_volume.powf(factor) * std::u16::MAX as f32; | |
new_volume.round() as u16 | |
} | |
fn main() { | |
let max_volume = 70; | |
for vol in 0..max_volume { | |
println!( | |
"{}: {}", | |
vol, | |
compute_volume_using_gauss_formula(vol, 3, 45, 52) | |
); | |
println!( | |
"{}: {}", | |
vol, | |
compute_volume_using_gauss_loop(vol, 3, 45, 50) | |
); | |
println!("{}: {}", vol, compute_volume_using_scale_factor(vol, 4.2)); | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use test::black_box; | |
#[bench] | |
fn raise_volume_with_for_loop(b: &mut test::Bencher) { | |
let volume = 70; | |
b.iter(|| { | |
for vol in 0..volume { | |
black_box(compute_volume_using_gauss_loop(vol, 3, 45, 50)); | |
} | |
}) | |
} | |
#[bench] | |
fn raise_volume_with_formula(b: &mut test::Bencher) { | |
let volume = 70; | |
b.iter(|| { | |
for vol in 0..volume { | |
black_box(compute_volume_using_gauss_formula(vol, 3, 45, 52)); | |
} | |
}) | |
} | |
#[bench] | |
fn raise_volume_with_scale_factor(b: &mut test::Bencher) { | |
let volume = 70; | |
b.iter(|| { | |
for vol in 0..volume { | |
black_box(compute_volume_using_scale_factor(vol, 4.2)); | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment