Created
August 31, 2016 00:19
-
-
Save will/9670b5785171210ff062f1f1e8dcabca to your computer and use it in GitHub Desktop.
InsecureRandom benchmarks
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
# I wanted to make InsecureRandom.uuid to speed up specs, but | |
require 'securerandom' | |
require 'benchmark/ips' | |
Benchmark.ips do |x| | |
x.report("sec") { SecureRandom.random_bytes(16) } | |
x.report("rand") { Random::DEFAULT.bytes(16) } | |
end if ARGV[0] == '1' | |
# non secure is faster, which makes sense, so we should be able to use that to make InsecureRandom.uuid | |
# sec 725.230k (± 9.6%) i/s - 3.636M in 5.068545s | |
# rand 5.470M (±12.0%) i/s - 27.096M in 5.036877s | |
# SecureRandom.uuid is implemented like this | |
# File securerandom.rb, line 246 | |
# def self.uuid | |
# ary = self.random_bytes(16).unpack("NnnnnN") | |
# ary[2] = (ary[2] & 0x0fff) | 0x4000 | |
# ary[3] = (ary[3] & 0x3fff) | 0x8000 | |
# "%08x-%04x-%04x-%04x-%04x%08x" % ary | |
# end | |
module InsecureRandom | |
def self.uuid | |
ary = Random::DEFAULT.bytes(16).unpack("NnnnnN") | |
ary[2] = (ary[2] & 0x0fff) | 0x4000 | |
ary[3] = (ary[3] & 0x3fff) | 0x8000 | |
"%08x-%04x-%04x-%04x-%04x%08x" % ary | |
end | |
end | |
Benchmark.ips do |x| | |
x.report("insecure") { InsecureRandom.uuid } | |
x.report(" secure") { SecureRandom.uuid } | |
end if ARGV[0] = '2' | |
# insecure 184.782k (±32.6%) i/s - 795.504k in 5.015430s | |
# secure 193.009k (±10.9%) i/s - 961.128k in 5.042140s | |
# but it isn't actually any faster. Is either unpack or printf actually that | |
# slow that it dominates the time? |
granted, SecureRandom should just implement that same trick.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
try