fastrand/
fastrand.rs

1// Copyright 2023 The rust-ggstd authors.
2// SPDX-License-Identifier: 0BSD
3
4// This example shows fastrand pseudorandom number generator.
5//
6// fastrand is used internally in Go standard library, but not exposed
7// to the users of the library.
8//
9// In rust-ggstd it is exposed as a number of functions in ggstd::runtime.
10// On first use fastrand is seeded with random data provided by the operating
11// system.
12//
13// fastrand is much faster than the global math::rand functions and slighly
14// faster than math::rand::Rand:
15//
16//   $ cargo run --example fastrand --release
17//     fastrand:              19 ms
18//     math::rand global:    352 ms
19//     math::rand::Rand:      20 ms
20
21use ggstd::math::rand;
22
23fn main() {
24    println!("{:08x}", ggstd::runtime::fastrand());
25    println!("{:08x}", ggstd::runtime::fastrand());
26    println!("{:16x}", ggstd::runtime::fastrand64());
27    println!("{:16x}", ggstd::runtime::fastrand64());
28    println!("{:x}", ggstd::runtime::fastrandu());
29    println!("{:x}", ggstd::runtime::fastrandu());
30    println!("{}", ggstd::runtime::fastrandn(100));
31    println!("{}", ggstd::runtime::fastrandn(100));
32    println!();
33
34    // testing speed
35    {
36        use std::time::Instant;
37
38        let count = 10_000_000;
39
40        {
41            let start_time = Instant::now();
42            for _ in 0..count {
43                ggstd::runtime::fastrandn(1_000_000_000);
44            }
45            let elapsed = Instant::now().duration_since(start_time);
46            println!("fastrand:          {:6} ms", elapsed.as_millis());
47        }
48
49        {
50            let start_time = Instant::now();
51            for _ in 0..count {
52                rand::int31n(1_000_000_000);
53            }
54            let elapsed = Instant::now().duration_since(start_time);
55            println!("math::rand global: {:6} ms", elapsed.as_millis());
56        }
57
58        {
59            let start_time = Instant::now();
60            let mut r = rand::Rand::new(rand::new_source(123));
61            for _ in 0..count {
62                r.int31n(1_000_000_000);
63            }
64            let elapsed = Instant::now().duration_since(start_time);
65            println!("math::rand::Rand:  {:6} ms", elapsed.as_millis());
66        }
67    }
68}