libc has random
which
uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers
I'm looking for a random function written in Rust with the same speed. It doesn't need to be crypto-safe, pseudo-random is good enough.
Looking through the rand crate
it seems that XorShiftRng
is the closest fit to this need:
The Xorshift algorithm is not suitable for cryptographic purposes but is very fast
When I use it like this:
extern crate time;
use rand::Rng;
let mut rng = rand::XorShiftRng::new_unseeded();
rng.next_u64();
it is about 33% slower than libc's random. (Sample code generating 8'000'000 random numbers).
In the end, I'll need i64
random numbers, so when I run rng.gen()
this is already 100% slower than libc's random. When casting with rng.next_u64() as i64
, then is is 60% slower.
Is there any way to achieve the same speed in rust without using any unsafe
code?
XorShiftRng
version withrng.gen()
is 760'000x as fast asrandom()
. So my case is solved, but I don't understand why the release version is so much faster, and why XorShiftRng is now so much faster thanrandom()
– hansaplastlet start = time(); let end = time(); println!("...", start.to(end));
. This only happens for XorShiftRng because its implementation is available to the compiler, whereas the libc::random is dynamically loaded at run-time. My suggestion would be to use a realistic workload to evaluate them. – Matthieu M.