Ruby MD5 and SHA1 Digest Benchmark
I did a benchmark of MD5 and SHA1 digests in Ruby. The benchmark was done in Ruby 1.8.6 on Windows.
The code used to benchmark:
require 'benchmark'
require 'digest/sha1'
require 'digest/md5'
require 'base64'
# Demonstration of digests
puts "SHA1.hexdigest #{Digest::SHA1.hexdigest('test')}"
puts "MD5.hexdigest #{Digest::MD5.hexdigest('test')}"
puts "SHA1.digest #{Base64.encode64(Digest::SHA1.digest('test'))}"
puts "MD5.digest #{Base64.encode64(Digest::MD5.digest('test'))}"
puts "MD5.digest.inspect #{Digest::MD5.digest('test').inspect}"
print "\nSHA1.digest bytes "
Digest::SHA1.digest('test').each_byte {|c| printf("%4d", c) }
print "\nMD5.digest bytes "
Digest::MD5.digest( 'test').each_byte {|c| printf("%4d", c) }
puts "\n\n"
# Benchmark
TIMES = 50_000
Benchmark.bmbm do |b|
b.report("sha1 hexdig") { TIMES.times do |x|; Digest::SHA1.hexdigest(x.to_s); end }
b.report("md5 hexdig") { TIMES.times do |x|; Digest::MD5.hexdigest(x.to_s); end }
b.report("sha1 digest") { TIMES.times do |x|; Digest::SHA1.digest(x.to_s); end }
b.report("md5 digest") { TIMES.times do |x|; Digest::MD5.digest(x.to_s); end }
end
The output:
SHA1.hexdigest a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
MD5.hexdigest 098f6bcd4621d373cade4e832627b4f6
SHA1.digest qUqP5cyxm6YcTAhz05Hph5gvu9M=
MD5.digest CY9rzUYh03PK3k6DJie09g==
MD5.digest.inspect "\t\217k\315F!\323s\312\336N\203&'\264\366"
SHA1.digest bytes 169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211
MD5.digest bytes 9 143 107 205 70 33 211 115 202 222 78 131 38 39 180 246
Rehearsal -----------------------------------------------
sha1 hexdig 0.797000 0.000000 0.797000 ( 0.796000)
md5 hexdig 0.641000 0.000000 0.641000 ( 0.641000)
sha1 digest 0.625000 0.000000 0.625000 ( 0.625000)
md5 digest 0.500000 0.000000 0.500000 ( 0.500000)
-------------------------------------- total: 2.563000sec
user system total real
sha1 hexdig 0.750000 0.032000 0.782000 ( 0.781000)
md5 hexdig 0.593000 0.000000 0.593000 ( 0.594000)
sha1 digest 0.594000 0.031000 0.625000 ( 0.625000)
md5 digest 0.469000 0.000000 0.469000 ( 0.468000)
As expected, digest methods are faster than hexdigest and MD5 is faster than SHA1.