Skip to content

Commit 3dfc6de

Browse files
committed
bench: use seeded RNG for deterministic benchmark results
Replace thread_rng() with StdRng::seed_from_u64() to ensure benchmarks use the same random inputs across runs, eliminating variance from different random numbers having vastly different primality testing times.
1 parent e170069 commit 3dfc6de

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

bench/benches/bench.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ use num_bigint::RandBigInt;
88
use num_prime::{nt_funcs, RandPrime};
99
#[cfg(feature = "num-primes")]
1010
use num_primes::{Generator, Verification};
11+
use rand::rngs::StdRng;
12+
use rand::SeedableRng;
1113

1214
#[cfg(target_arch = "x86_64")]
1315
use number_theory::NumberTheory;
@@ -51,7 +53,7 @@ pub fn bench_is_prime(c: &mut Criterion) {
5153

5254
////// 256 bits Bigint /////
5355

54-
let mut rng = rand::thread_rng();
56+
let mut rng = StdRng::seed_from_u64(42);
5557
let numbers: Vec<_> = repeat_with(|| rng.gen_biguint(256)).take(32).collect();
5658

5759
let mut group = c.benchmark_group("primality check (u256)");
@@ -117,7 +119,7 @@ pub fn bench_is_prime(c: &mut Criterion) {
117119

118120
////// 2048 bits Bigint /////
119121

120-
let mut rng = rand::thread_rng();
122+
let mut rng = StdRng::seed_from_u64(123);
121123
let numbers: Vec<_> = repeat_with(|| rng.gen_biguint(2048)).take(8).collect();
122124

123125
let mut group = c.benchmark_group("primality check (u2048)");
@@ -215,7 +217,7 @@ pub fn bench_prime_gen(c: &mut Criterion) {
215217
let mut group = c.benchmark_group("prime generation (256 bits)");
216218
group.sample_size(10).sampling_mode(SamplingMode::Flat);
217219

218-
let mut rng = rand::thread_rng();
220+
let mut rng = StdRng::seed_from_u64(256);
219221
group.bench_function("num-prime (this crate)", |b| {
220222
b.iter(|| -> num_bigint::BigUint { rng.gen_prime(256, None) })
221223
});
@@ -226,7 +228,7 @@ pub fn bench_prime_gen(c: &mut Criterion) {
226228
let mut group = c.benchmark_group("safe prime generation (256 bits)");
227229
group.sample_size(10).sampling_mode(SamplingMode::Flat);
228230

229-
let mut rng = rand::thread_rng();
231+
let mut rng = StdRng::seed_from_u64(512);
230232
group.bench_function("num-prime (this crate)", |b| {
231233
b.iter(|| -> num_bigint::BigUint { rng.gen_safe_prime(256) })
232234
});

0 commit comments

Comments
 (0)