Skip to content

Instantly share code, notes, and snippets.

@kigster
Last active August 17, 2019 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kigster/a02ac30ff5f347508cb706f894894795 to your computer and use it in GitHub Desktop.
Save kigster/a02ac30ff5f347508cb706f894894795 to your computer and use it in GitHub Desktop.
Comparing time to compute SHA1 of integers using pure Ruby, Ruby threads, and Forking
#!/usr/bin/env ruby
#
# To run this example, do first: `gem install parallel`
#
# Simple Benchmark on a 16-Core MacBook PRO:
#
# Number of CPU Cores: 16, total iterations: 10000
#
# user system total real
# ruby/01T 0.054921 0.000947 0.055868 ( 0.055886)
# ruby/16T 0.059477 0.001923 0.061400 ( 0.059579)
# ruby/16P 3.776095 16.852467 247.631315 ( 36.405558)
require 'digest'
require 'benchmark'
require 'parallel'
require 'fileutils'
require 'etc'
@num_cpus = Etc.nprocessors
@iterations = (ARGV[0] || 50000).to_i
puts "Number of CPU Cores: #{@num_cpus}, total iterations: #{@iterations}"
def sha1ruby(value)
sprintf "%5d %s\n", value, Digest::SHA1.digest(value.to_s).bytes.map{ |b| b.to_s(16) }.join
end
def sha1proc(value)
var = `/usr/local/bin/bash -c "printf #{value} | /usr/local/bin/sha1sum"`.chomp.split(/ /).first
sprintf "%5d %s\n", value, var
end
Benchmark.bm do |bm|
title = "ruby/01T"
bm.report(title) do
Parallel.map((0...@iterations).to_a, in_threads: 1) do |i|
sha1ruby(i)
end
end
title = "ruby/#{@num_cpus}T"
bm.report(title) do
Parallel.map((0...@iterations).to_a, in_threads: @num_cpus) do |i|
sha1ruby(i)
end
end
title = "ruby/#{@num_cpus}P"
bm.report(title) do
Parallel.map((0...@iterations).to_a, in_threads: @num_cpus) do |i|
sha1proc(i)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment