我经常需要随机字节来测试字节缓冲区上的各种方法。现在我正在使用 SecureRandom.random_bytes
但由于它需要安全,所以速度很慢。对于这种情况,是否有使用 C 扩展来快速生成随机字节的替代方法?
更新:
最简单的方法是使用 Random.new
而不是 SecureRandom
。
require 'securerandom'
require 'benchmark'
Benchmark.bm(12) do |x|
x.report("SecureRandom:") { 100.times { SecureRandom.random_bytes(1024*1024*5) } }
x.report("Random:") { 100.times { Random.new.bytes(1024*1024*5) } }
end
交付:
user system total real
SecureRandom: 15.510000 0.170000 15.680000 ( 15.952913)
Random: 0.920000 0.120000 1.040000 ( 1.070739)
最佳答案
在 Random
类 bytes
方法中,您必须传递字节的大小,这将为您提供一些技巧
Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
关于ruby - Ruby 中的快速(不安全)随机字节生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34264402/