|
| 1 | +use rust_data_structures::linked_list::LinkedList; |
| 2 | +use rust_data_structures::vector::Vector; |
| 3 | +use std::hint::black_box; |
| 4 | +use std::time::{Duration, Instant}; |
| 5 | + |
| 6 | +const SIZE: usize = 20_000; |
| 7 | + |
| 8 | +fn main() { |
| 9 | + println!("linked list benchmark (manual, std::time::Instant)"); |
| 10 | + println!("size: {SIZE}"); |
| 11 | + println!("push_front: {:?}", bench_push_front()); |
| 12 | + println!("push_back: {:?}", bench_push_back()); |
| 13 | + println!("pop_front: {:?}", bench_pop_front()); |
| 14 | + println!("iterate linked list: {:?}", bench_linked_list_iteration()); |
| 15 | + println!("iterate vector: {:?}", bench_vector_iteration()); |
| 16 | +} |
| 17 | + |
| 18 | +fn bench_push_front() -> Duration { |
| 19 | + let start = Instant::now(); |
| 20 | + let mut list = LinkedList::new(); |
| 21 | + |
| 22 | + for value in 0..SIZE { |
| 23 | + list.push_front(black_box(value)); |
| 24 | + } |
| 25 | + |
| 26 | + black_box(list.len()); |
| 27 | + start.elapsed() |
| 28 | +} |
| 29 | + |
| 30 | +fn bench_push_back() -> Duration { |
| 31 | + let start = Instant::now(); |
| 32 | + let mut list = LinkedList::new(); |
| 33 | + |
| 34 | + for value in 0..SIZE { |
| 35 | + list.push_back(black_box(value)); |
| 36 | + } |
| 37 | + |
| 38 | + black_box(list.len()); |
| 39 | + start.elapsed() |
| 40 | +} |
| 41 | + |
| 42 | +fn bench_pop_front() -> Duration { |
| 43 | + let mut list = LinkedList::new(); |
| 44 | + for value in 0..SIZE { |
| 45 | + list.push_back(value); |
| 46 | + } |
| 47 | + |
| 48 | + let start = Instant::now(); |
| 49 | + while let Some(value) = list.pop_front() { |
| 50 | + black_box(value); |
| 51 | + } |
| 52 | + |
| 53 | + start.elapsed() |
| 54 | +} |
| 55 | + |
| 56 | +fn bench_linked_list_iteration() -> Duration { |
| 57 | + let mut list = LinkedList::new(); |
| 58 | + for value in 0..SIZE { |
| 59 | + list.push_front(value); |
| 60 | + } |
| 61 | + |
| 62 | + let start = Instant::now(); |
| 63 | + let sum: usize = list.iter().copied().map(black_box).sum(); |
| 64 | + |
| 65 | + black_box(sum); |
| 66 | + start.elapsed() |
| 67 | +} |
| 68 | + |
| 69 | +fn bench_vector_iteration() -> Duration { |
| 70 | + let mut vector = Vector::with_capacity(SIZE); |
| 71 | + for value in 0..SIZE { |
| 72 | + vector.push(value); |
| 73 | + } |
| 74 | + |
| 75 | + let start = Instant::now(); |
| 76 | + let sum: usize = vector.iter().copied().map(black_box).sum(); |
| 77 | + |
| 78 | + black_box(sum); |
| 79 | + start.elapsed() |
| 80 | +} |
0 commit comments