4

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)

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.