test binary search against linear search
This commit is contained in:
99
src/main.rs
Normal file
99
src/main.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use std::time::{Duration, Instant};
|
||||
use rand::random;
|
||||
|
||||
fn main() {
|
||||
for i in 1..400 {
|
||||
let result = test_searches(500000 / i, i*2);
|
||||
println!("{} {} {}",
|
||||
result[0].as_nanos(), result[1].as_nanos(), result[2].as_nanos());
|
||||
}
|
||||
}
|
||||
|
||||
fn test_searches(runs: usize, items: usize) -> Vec<Duration> {
|
||||
let mut lists: Vec<Vec<u64>> = Vec::new();
|
||||
let mut needles: Vec<u64> = Vec::new();
|
||||
|
||||
for _ in 0..runs {
|
||||
let mut current_list: Vec<u64> = Vec::new();
|
||||
|
||||
for _ in 0..items {
|
||||
current_list.push(random::<u64>());
|
||||
}
|
||||
|
||||
needles.push(current_list[0]);
|
||||
current_list.sort();
|
||||
lists.push(current_list);
|
||||
}
|
||||
|
||||
flush_caches();
|
||||
|
||||
let start_time = Instant::now();
|
||||
for i in 0..runs {
|
||||
search_linear_functional(&lists[i], needles[i]);
|
||||
}
|
||||
let linear_functional_duration = Instant::now().duration_since(start_time);
|
||||
|
||||
flush_caches();
|
||||
|
||||
let start_time = Instant::now();
|
||||
for i in 0..runs {
|
||||
search_linear_naive(&lists[i], needles[i]);
|
||||
}
|
||||
let linear_naive_duration = Instant::now().duration_since(start_time);
|
||||
|
||||
flush_caches();
|
||||
|
||||
let start_time = Instant::now();
|
||||
for i in 0..runs {
|
||||
search_binary(&lists[i], needles[i]);
|
||||
}
|
||||
let binary_duration = Instant::now().duration_since(start_time);
|
||||
|
||||
eprintln!("Tested {} runs of {} items each", runs, items);
|
||||
|
||||
vec![linear_functional_duration, linear_naive_duration, binary_duration]
|
||||
}
|
||||
|
||||
fn flush_caches() {
|
||||
let mut rnd: Vec<u64> = Vec::new();
|
||||
|
||||
for _ in 0..10*1024*1024 {
|
||||
rnd.push(random::<u64>());
|
||||
}
|
||||
|
||||
for i in 0..10*1024*1024 {
|
||||
if rnd[i] == i as u64 {
|
||||
eprintln!("that's a strange coincidence!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn search_binary(haystack: &[u64], needle: u64) {
|
||||
let index = haystack.binary_search(&needle).unwrap();
|
||||
|
||||
if index as u64 == needle {
|
||||
eprintln!("that's a strange coincidence!");
|
||||
}
|
||||
}
|
||||
|
||||
fn search_linear_functional(haystack: &[u64], needle: u64) {
|
||||
let index = haystack.iter().enumerate().skip_while(|(_,x)|**x != needle).next().unwrap().0;
|
||||
|
||||
if index as u64 == needle {
|
||||
eprintln!("that's a strange coincidence!");
|
||||
}
|
||||
}
|
||||
|
||||
fn search_linear_naive(haystack: &[u64], needle: u64) {
|
||||
let mut index = 0;
|
||||
for i in 0..haystack.len() {
|
||||
if haystack[i] == needle {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if index as u64 == needle {
|
||||
eprintln!("that's a strange coincidence!");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user