1 // Copyright 2019 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 #![feature(test)]
10
11 extern crate test;
12
13 use rand::distributions::WeightedIndex;
14 use rand::Rng;
15 use test::Bencher;
16
17 #[bench]
weighted_index_creation(b: &mut Bencher)18 fn weighted_index_creation(b: &mut Bencher) {
19 let mut rng = rand::thread_rng();
20 let weights = [1u32, 2, 4, 0, 5, 1, 7, 1, 2, 3, 4, 5, 6, 7];
21 b.iter(|| {
22 let distr = WeightedIndex::new(weights.to_vec()).unwrap();
23 rng.sample(distr)
24 })
25 }
26
27 #[bench]
weighted_index_modification(b: &mut Bencher)28 fn weighted_index_modification(b: &mut Bencher) {
29 let mut rng = rand::thread_rng();
30 let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7];
31 let mut distr = WeightedIndex::new(weights.to_vec()).unwrap();
32 b.iter(|| {
33 distr.update_weights(&[(2, &4), (5, &1)]).unwrap();
34 rng.sample(&distr)
35 })
36 }
37