使用基准测试,您可以测试和测量代码的速度,但是基准测试仍然不稳定。要在您的货运项目中启用基准测试,您需要每晚进行防锈工作,将集成基准测试benches/放在Cargo项目根目录下的文件夹中,然后运行cargo bench。
来自llogiq.github.io的示例
extern crate test; extern crate rand; use test::Bencher; use rand::Rng; use std::mem::replace; #[bench] fn empty(b: &mut Bencher) { b.iter(|| 1) } #[bench] fn setup_random_hashmap(b: &mut Bencher) { let mut val : u32 = 0; let mut rng = rand::IsaacRng::new_unseeded(); let mut map = std::collections::HashMap::new(); b.iter(|| { map.insert(rng.gen::<u8>() as usize, val); val += 1; }) } #[bench] fn setup_random_vecmap(b: &mut Bencher) { let mut val : u32 = 0; let mut rng = rand::IsaacRng::new_unseeded(); let mut map = std::collections::VecMap::new(); b.iter(|| { map.insert((rng.gen::<u8>()) as usize, val); val += 1; }) } #[bench] fn setup_random_vecmap_cap(b: &mut Bencher) { let mut val : u32 = 0; let mut rng = rand::IsaacRng::new_unseeded(); let mut map = std::collections::VecMap::with_capacity(256); b.iter(|| { map.insert((rng.gen::<u8>()) as usize, val); val += 1; }) }