diff --git a/sort/Cargo.toml b/sort/Cargo.toml index 4ba1567f..45df398b 100644 --- a/sort/Cargo.toml +++ b/sort/Cargo.toml @@ -6,3 +6,10 @@ publish = false [dependencies] rand = "0.8.5" + +[dev-dependencies] +criterion = "0.5.1" + +[[bench]] +name = "bubble_sort" +harness = false \ No newline at end of file diff --git a/sort/benches/bubble_sort.rs b/sort/benches/bubble_sort.rs new file mode 100644 index 00000000..be3bdc28 --- /dev/null +++ b/sort/benches/bubble_sort.rs @@ -0,0 +1,10 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +use criterion::{Criterion, criterion_group, criterion_main}; + +fn criterion_benchmark(_c: &mut Criterion) {} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/sort/src/util.rs b/sort/src/util.rs index 18315be8..e4431181 100644 --- a/sort/src/util.rs +++ b/sort/src/util.rs @@ -3,7 +3,8 @@ // in the LICENSE file. use std::fmt; -use std::io::{self, BufRead, BufReader}; +use std::fs::File; +use std::io::{self, BufRead, BufReader, Read}; pub fn is_sorted(list: &[T]) -> bool where @@ -74,3 +75,34 @@ pub fn read_strings() -> Vec { } v } + +/// Generate random integers. +/// +/// # Errors +/// Returns error if failed to rand system random file. +pub fn random_ints(len: usize) -> Result, io::Error> { + let mut file = File::open("/dev/urandom")?; + let mut buf = vec![0; len * 4]; + file.read_exact(&mut buf)?; + + let mut nums = Vec::with_capacity(len); + for i in 0..len { + let array: [u8; 4] = [buf[4 * i], buf[4 * i + 1], buf[4 * i + 2], buf[4 * i + 3]]; + // let mut array: [u8; 4] = [0; 4]; + // array.swap_with_slice(&mut buf[(i * 4)..(i * 4 + 4)]); + nums.push(i32::from_le_bytes(array)); + } + Ok(nums) +} + +#[cfg(test)] +mod tests { + use crate::util::random_ints; + + #[test] + fn test_random_ints() { + let len = 100; + let nums: Vec = random_ints(len).unwrap(); + assert_eq!(nums.len(), len); + } +} \ No newline at end of file