Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast (insecure) random bytes generator in Ruby

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)
like image 960
Julik Avatar asked Sep 13 '25 20:09

Julik


1 Answers

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

like image 156
punitcse Avatar answered Sep 15 '25 14:09

punitcse