I often need random bytes to test various methods over byte buffers. For now I am using SecureRandom.random_bytes
but it is slow-ish by virtue of it's requirement to be secure. Is there an alternative that uses a C extension for quick generation of random bytes for this sort of situations?
UPDATE:
The easiest thing is to use Random.new
instead of 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
delivers:
user system total real
SecureRandom: 15.510000 0.170000 15.680000 ( 15.952913)
Random: 0.920000 0.120000 1.040000 ( 1.070739)
In Random
class bytes
method you have to pass the size of bytes that will do the trick for you example
Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
for more reference here http://ruby-doc.org/core-2.2.0/Random.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With