Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Random Base-36 Benchmark
require 'benchmark'
n = 1_000_000
(1..50).step(5) do |length|
puts "Length: #{length}"
Benchmark.bm do |x|
x.report('array') { n.times { Array.new(length) { rand(36).to_s(36) }.join } }
x.report('exponentiation') { n.times { rand(36**length).to_s(36).rjust(length, '0') } }
end
end
# Length: 1
# user system total real
# array 1.190000 0.010000 1.200000 ( 1.205521)
# exponentiation 0.410000 0.000000 0.410000 ( 0.413634)
# Length: 6
# user system total real
# array 3.710000 0.010000 3.720000 ( 3.719449)
# exponentiation 0.530000 0.000000 0.530000 ( 0.533168)
# Length: 11
# user system total real
# array 5.920000 0.010000 5.930000 ( 5.929622)
# exponentiation 0.600000 0.000000 0.600000 ( 0.600140)
# Length: 16
# user system total real
# array 8.150000 0.010000 8.160000 ( 8.159749)
# exponentiation 1.190000 0.000000 1.190000 ( 1.196643)
# Length: 21
# user system total real
# array 10.490000 0.010000 10.500000 ( 10.508310)
# exponentiation 1.600000 0.000000 1.600000 ( 1.599446)
# Length: 26
# user system total real
# array 12.700000 0.010000 12.710000 ( 12.713277)
# exponentiation 1.870000 0.010000 1.880000 ( 1.875399)
# Length: 31
# user system total real
# array 14.960000 0.010000 14.970000 ( 14.973472)
# exponentiation 2.240000 0.000000 2.240000 ( 2.241677)
# Length: 36
# user system total real
# array 17.390000 0.020000 17.410000 ( 17.416817)
# exponentiation 2.440000 0.000000 2.440000 ( 2.447508)
# Length: 41
# user system total real
# array 19.540000 0.020000 19.560000 ( 19.562576)
# exponentiation 3.190000 0.000000 3.190000 ( 3.193456)
# Length: 46
# user system total real
# array 21.690000 0.020000 21.710000 ( 21.712321)
# exponentiation 3.690000 0.010000 3.700000 ( 3.702962)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.