Created
July 19, 2018 15:54
-
-
Save pftbest/7ad27661ad2e3bdd871f5bb88dd8beae to your computer and use it in GitHub Desktop.
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; | |
trait Max2 { | |
type Item; | |
fn max_by_key2<B: Ord, F>(self, f: F) -> Option<Self::Item> where | |
Self: Sized, | |
F: FnMut(&Self::Item) -> B; | |
} | |
impl<I, T> Max2 for T where T: Iterator<Item = I> { | |
type Item = I; | |
fn max_by_key2<B: Ord, F>(mut self, mut f: F) -> Option<Self::Item> where | |
Self: Sized, | |
F: FnMut(&Self::Item) -> B { | |
let mut max_el; | |
let mut max_val; | |
match (&mut self).next() { | |
Some(x) => { | |
max_val = f(&x); | |
max_el = x; | |
}, | |
None => return None, | |
} | |
for x in self { | |
let new_val = f(&x); | |
if new_val >= max_val { | |
max_val = new_val; | |
max_el = x; | |
} | |
} | |
Some(max_el) | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use test::Bencher; | |
#[allow(dead_code)] | |
struct Data { | |
k: i32, | |
z: i8, | |
} | |
fn get_data() -> Vec<Data> { | |
const N: usize = 10000; | |
let mut v = Vec::with_capacity(N); | |
for i in 0..N { | |
v.push(Data { | |
k: i as i32, | |
z: 48, | |
}); | |
} | |
v | |
} | |
#[bench] | |
fn bench_max_by_key(b: &mut Bencher) { | |
let v = get_data(); | |
b.iter(|| v.iter().max_by_key(|x| x.k)); | |
} | |
#[bench] | |
fn bench_max_by_key2(b: &mut Bencher) { | |
let v = get_data(); | |
b.iter(|| v.iter().max_by_key2(|x| x.k)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment