生成随机数的最快方法
Fastest way to generate random numbers
libc 有 random
其中
uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers
我正在寻找以相同速度用 Rust 编写的随机函数。它不需要加密安全,伪随机就足够了。
浏览 rand crate
it seems that XorShiftRng
最符合此需求:
The Xorshift algorithm is not suitable for cryptographic purposes but is very fast
当我这样使用它时:
extern crate time;
use rand::Rng;
let mut rng = rand::XorShiftRng::new_unseeded();
rng.next_u64();
比libc的random慢了大约33%。 (Sample code generating 8'000'000 random numbers).
最后,我需要 i64
个随机数,所以当我 运行 rng.gen()
这已经比 libc 的随机数慢了 100%。当用 rng.next_u64() as i64
投射时,速度会慢 60%。
有没有什么方法可以在不使用任何 unsafe
代码的情况下在 Rust 中达到相同的速度?
确保在发布模式下编译您正在测量的代码,否则您的基准测试不能代表 Rust 的性能。
为了获得有意义的数字,您还必须修改基准以对生成的数字做一些事情,例如将它们收集到一个向量1中。不这样做会使编译器优化整个循环,因为它没有副作用。这是您第二次尝试时发生的情况,导致您得出结论 XorShiftRng
比 libc::random
快 760,000 千倍。
在 changed benchmark 运行 处于发布模式时,XorShiftRng
最终比 libc::random
快大约 2 倍:
PT0.101378490S seconds for libc::random
PT0.050827393S seconds for XorShiftRng
1
编译器也可以足够聪明地意识到向量也未被使用,并将其优化掉,但当前 rustc
不会这样做,将元素存储到向量中就足够了。确保这一代未被优化掉的一种简单且面向未来的方法是对数字求和并写出结果。
libc 有 random
其中
uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers
我正在寻找以相同速度用 Rust 编写的随机函数。它不需要加密安全,伪随机就足够了。
浏览 rand crate
it seems that XorShiftRng
最符合此需求:
The Xorshift algorithm is not suitable for cryptographic purposes but is very fast
当我这样使用它时:
extern crate time;
use rand::Rng;
let mut rng = rand::XorShiftRng::new_unseeded();
rng.next_u64();
比libc的random慢了大约33%。 (Sample code generating 8'000'000 random numbers).
最后,我需要 i64
个随机数,所以当我 运行 rng.gen()
这已经比 libc 的随机数慢了 100%。当用 rng.next_u64() as i64
投射时,速度会慢 60%。
有没有什么方法可以在不使用任何 unsafe
代码的情况下在 Rust 中达到相同的速度?
确保在发布模式下编译您正在测量的代码,否则您的基准测试不能代表 Rust 的性能。
为了获得有意义的数字,您还必须修改基准以对生成的数字做一些事情,例如将它们收集到一个向量1中。不这样做会使编译器优化整个循环,因为它没有副作用。这是您第二次尝试时发生的情况,导致您得出结论 XorShiftRng
比 libc::random
快 760,000 千倍。
在 changed benchmark 运行 处于发布模式时,XorShiftRng
最终比 libc::random
快大约 2 倍:
PT0.101378490S seconds for libc::random
PT0.050827393S seconds for XorShiftRng
1
编译器也可以足够聪明地意识到向量也未被使用,并将其优化掉,但当前 rustc
不会这样做,将元素存储到向量中就足够了。确保这一代未被优化掉的一种简单且面向未来的方法是对数字求和并写出结果。