Last active
August 11, 2023 22:19
-
-
Save pboling/9601351c635a4fff62c9bbeb2fc146e6 to your computer and use it in GitHub Desktop.
Ruby Random: Performance vs. Distribution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark' | |
gem 'securerandom' | |
gem 'openssl' | |
gem 'ruby-statistics', require: 'statistics' | |
end | |
# Random space is 0 to x, non-inclusive | |
x = 15 | |
# Run 50k iterations | |
n = 50_000 | |
Benchmark.bmbm do |b| | |
b.report("K.rand:") { 1.upto(n) { Kernel.rand(x) } } | |
b.report("R.rand:") { 1.upto(n) { Random.rand(x) } } | |
b.report("S.rand:") { 1.upto(n) { SecureRandom.rand(x) } } | |
# This is the only one that will result in cryptographically secure random number generation | |
b.report("O.rand:") { 1.upto(n) { OpenSSL::Random.random_bytes(4).unpack("S")[0].modulo(x) } } | |
end | |
# Run 50k iterations | |
n = 50_000 | |
k = Hash.new(0) | |
r = Hash.new(0) | |
s = Hash.new(0) | |
o = Hash.new(0) | |
puts "*** Standard Deviations: Generating random numbers from 0 to #{x} ***" | |
1.upto(n) { k[Kernel.rand(x)] += 1 } | |
1.upto(n) { r[Random.rand(x)] += 1 } | |
1.upto(n) { s[SecureRandom.rand(x)] += 1 } | |
1.upto(n) { o[OpenSSL::Random.random_bytes(4).unpack("S")[0].modulo(x)] += 1 } | |
# Standard Deviations | |
ks = k.values | |
rs = r.values | |
ss = s.values | |
os = o.values | |
puts "\n*** Standard Deviations: Results ***\n" | |
puts "\n*** Kernel.rand ***\n" | |
puts ks.to_s | |
puts "mean: #{ks.mean}, std-dev: #{ks.standard_deviation}" | |
puts "\n*** Random.rand ***\n" | |
puts rs.to_s | |
puts "#{rs.mean}, std-dev: #{rs.standard_deviation}" | |
puts "\n*** SecureRandom.rand ***\n" | |
puts ss.to_s | |
puts "mean: #{ss.mean}, std-dev: #{ss.standard_deviation}" | |
puts "\n*** OpenSSL::Random.random_bytes ***\n" | |
puts os.to_s | |
puts "mean: #{os.mean}, std-dev: #{os.standard_deviation}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment