File size: 1,523 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
use std::path::PathBuf;
use rand::{SeedableRng, rngs::StdRng, seq::IndexedRandom};
use rustc_hash::FxHashMap;
/// Picks modules at random, but with a fixed seed so runs are somewhat
/// reproducible.
///
/// This must be initialized outside of `bench_with_input` so we don't repeat
/// the same sequence in different samples.
pub struct ModulePicker {
depths: Vec<usize>,
modules_by_depth: FxHashMap<usize, Vec<PathBuf>>,
rng: parking_lot::Mutex<StdRng>,
}
impl ModulePicker {
/// Creates a new module picker.
pub fn new(mut modules: Vec<(PathBuf, usize)>) -> Self {
let rng = StdRng::seed_from_u64(42);
// Ensure the module order is deterministic.
modules.sort();
let mut modules_by_depth: FxHashMap<_, Vec<_>> = FxHashMap::default();
for (module, depth) in modules {
modules_by_depth.entry(depth).or_default().push(module);
}
let mut depths: Vec<_> = modules_by_depth.keys().copied().collect();
// Ensure the depth order is deterministic.
depths.sort();
Self {
depths,
modules_by_depth,
rng: parking_lot::Mutex::new(rng),
}
}
/// Picks a random module with a uniform distribution over all depths.
pub fn pick(&self) -> &PathBuf {
let mut rng = self.rng.lock();
// Sample from all depths uniformly.
let depth = self.depths.choose(&mut *rng).unwrap();
self.modules_by_depth[depth].choose(&mut *rng).unwrap()
}
}
|