|
| 1 | +use core::cell::UnsafeCell; |
| 2 | +use criterion::{Criterion, black_box, criterion_group, criterion_main}; |
| 3 | +use embed_collections::avl::{AvlItem, AvlNode, AvlTree}; |
| 4 | +use rand::seq::SliceRandom; |
| 5 | +use rand::{Rng, thread_rng}; |
| 6 | +use std::fmt; |
| 7 | + |
| 8 | +// The same test setup from src/avl.rs |
| 9 | +struct IntAvlNode { |
| 10 | + pub value: i64, |
| 11 | + pub node: UnsafeCell<AvlNode<Self, ()>>, |
| 12 | +} |
| 13 | +unsafe impl Send for IntAvlNode {} |
| 14 | +impl fmt::Debug for IntAvlNode { |
| 15 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 16 | + write!(f, "{} {:#?}", self.value, self.node) |
| 17 | + } |
| 18 | +} |
| 19 | +unsafe impl AvlItem<()> for IntAvlNode { |
| 20 | + fn get_node(&self) -> &mut AvlNode<Self, ()> { |
| 21 | + unsafe { &mut *self.node.get() } |
| 22 | + } |
| 23 | +} |
| 24 | +fn new_intnode(i: i64) -> Box<IntAvlNode> { |
| 25 | + Box::new(IntAvlNode { node: UnsafeCell::new(AvlNode::default()), value: i }) |
| 26 | +} |
| 27 | +type IntAvlTree = AvlTree<Box<IntAvlNode>, ()>; |
| 28 | +fn new_inttree() -> IntAvlTree { |
| 29 | + AvlTree::<Box<IntAvlNode>, ()>::new() |
| 30 | +} |
| 31 | +fn cmp_int_node(a: &IntAvlNode, b: &IntAvlNode) -> std::cmp::Ordering { |
| 32 | + a.value.cmp(&b.value) |
| 33 | +} |
| 34 | + |
| 35 | +fn cmp_int(a: &i64, b: &IntAvlNode) -> std::cmp::Ordering { |
| 36 | + a.cmp(&b.value) |
| 37 | +} |
| 38 | + |
| 39 | +fn bench_avl_insert(c: &mut Criterion) { |
| 40 | + let count = 10000; |
| 41 | + let mut rng = thread_rng(); |
| 42 | + let mut values: Vec<i64> = (0..count).map(|_| rng.r#gen()).collect(); |
| 43 | + values.sort_unstable(); |
| 44 | + values.dedup(); |
| 45 | + |
| 46 | + c.bench_function("avl_insert_10000", |b| { |
| 47 | + b.iter(|| { |
| 48 | + let mut tree = new_inttree(); |
| 49 | + for &value in &values { |
| 50 | + tree.add(black_box(new_intnode(value)), cmp_int_node); |
| 51 | + } |
| 52 | + }) |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +fn bench_avl_search(c: &mut Criterion) { |
| 57 | + let count = 10000; |
| 58 | + let mut rng = thread_rng(); |
| 59 | + let mut values: Vec<i64> = (0..count).map(|_| rng.r#gen()).collect(); |
| 60 | + values.sort_unstable(); |
| 61 | + values.dedup(); |
| 62 | + |
| 63 | + let mut tree = new_inttree(); |
| 64 | + for &value in &values { |
| 65 | + tree.add(new_intnode(value), cmp_int_node); |
| 66 | + } |
| 67 | + |
| 68 | + values.shuffle(&mut rng); |
| 69 | + |
| 70 | + c.bench_function("avl_search_10000", |b| { |
| 71 | + b.iter(|| { |
| 72 | + for &value in &values { |
| 73 | + black_box(tree.find(&value, cmp_int)); |
| 74 | + } |
| 75 | + }) |
| 76 | + }); |
| 77 | +} |
| 78 | + |
| 79 | +criterion_group!(benches, bench_avl_insert, bench_avl_search); |
| 80 | +criterion_main!(benches); |
0 commit comments