Skip to content

Instantly share code, notes, and snippets.

@mbrubeck
Forked from pftbest/lib.rs
Last active July 19, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrubeck/0118a5a678b5a796b057e2515b67cdd4 to your computer and use it in GitHub Desktop.
Save mbrubeck/0118a5a678b5a796b057e2515b67cdd4 to your computer and use it in GitHub Desktop.
#![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 = self.next()?;
let mut max_val = f(&max_el);
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