Created
September 2, 2017 06:09
-
-
Save alexcrichton/aed8ef41b605aed133ddaec22fd87102 to your computer and use it in GitHub Desktop.
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
#![feature(test)] | |
extern crate test; | |
pub fn saturating_f32(a: f32) -> i32 { | |
if i32::min_value() as f32 <= a && a <= i32::max_value() as f32 { | |
a as i32 | |
} else if a.is_nan() { | |
0 | |
} else if a < 0.0 { | |
i32::min_value() | |
} else { | |
i32::max_value() | |
} | |
} | |
pub fn saturating_f64(a: f64) -> i32 { | |
if i32::min_value() as f64 <= a && a <= i32::max_value() as f64 { | |
a as i32 | |
} else if a.is_nan() { | |
0 | |
} else if a < 0.0 { | |
i32::min_value() | |
} else { | |
i32::max_value() | |
} | |
} | |
macro_rules! benches { | |
($name32:ident, $name64:ident) => { | |
float_benches!(f32, $name32); | |
float_benches!(f64, $name64); | |
} | |
} | |
macro_rules! float_benches { | |
($float:ident, $name:ident) => { | |
mod $name { | |
use std::$float; | |
#[bench] | |
fn nan(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, $float::NAN)) | |
} | |
#[bench] | |
fn inf_pos(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, $float::INFINITY)) | |
} | |
#[bench] | |
fn inf_neg(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, $float::NEG_INFINITY)) | |
} | |
#[bench] | |
fn min(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, $float::MIN)) | |
} | |
#[bench] | |
fn max(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, $float::MAX)) | |
} | |
#[bench] | |
fn neg_zero(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, -0.0)) | |
} | |
#[bench] | |
fn one(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, 1.0)) | |
} | |
#[bench] | |
fn neg_one(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, 1.0)) | |
} | |
#[bench] | |
fn max_plus_one(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, i32::max_value() as $float + 1.0)) | |
} | |
#[bench] | |
fn min_minus_one(b: &mut ::test::Bencher) { | |
b.iter(|| super::test(super::$name, i32::min_value() as $float - 1.0)) | |
} | |
} | |
} | |
} | |
fn as_cast_f32(a: f32) -> i32 { | |
a as i32 | |
} | |
fn as_cast_f64(a: f64) -> i32 { | |
a as i32 | |
} | |
fn test<F: FnMut(T) -> R, R, T>(mut f: F, t: T) | |
where T: Copy, | |
{ | |
for _ in 0..100 { | |
test::black_box(f(test::black_box(t))); | |
} | |
} | |
benches!(as_cast_f32, as_cast_f64); | |
benches!(saturating_f32, saturating_f64); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment