For writing a benchmark, I would like to use some random numbers. They wouldn't need to be cryptographically secure, so I wonder if the following approach is suitable:
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
fn main() {
let mut hasher = RandomState::new().build_hasher();
for _ in 0..10 {
hasher.write(&[0]);
let random = hasher.finish();
println!("{random}");
}
}
Some questions:
- Is this approach reasonably fast?
- Is there another, more idiomatic way to generate cheap random numbers?
- Is the chance of collision much higher than with a truly random number generator?
- Could this leak a pattern which interferes with usages of
HashMap
andHashSet
such that they become slower, e.g. if I would store such random number in aHashMap
/HashSet
which uses the same hashing algorithm?
Click here for a slightly nicer, encapsulated version (using the same algorithm)
use std::collections::hash_map::{DefaultHasher, RandomState};
use std::hash::{BuildHasher, Hasher};
pub struct RGen(DefaultHasher);
impl RGen {
pub fn new() -> Self {
RGen(RandomState::new().build_hasher())
}
pub fn random(&mut self) -> u64 {
self.0.write(&[0]);
self.0.finish()
}
}
fn main() {
let mut g = RGen::new();
for _ in 0..10 {
let random = g.random();
println!("{random}");
}
}
(Playground of encapsulated version)