Skip to content

Commit

Permalink
Worker example and parallel hash benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed Apr 9, 2012
1 parent 19739fb commit 73e40da
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
15 changes: 15 additions & 0 deletions benchmarks/parallel_hash.rb
@@ -0,0 +1,15 @@
#!/usr/bin/env ruby

require 'rubygems'
require 'bundler/setup'
require 'celluloid'
require 'benchmark/ips'
require File.expand_path("../../examples/worker", __FILE__)

pool = Rehasher.new

Benchmark.ips do |ips|
ips.report("parallel hash") do
64.times.map { pool.future(:rehash, 'w3rd', 10_000) }.map(&:value)
end
end
39 changes: 39 additions & 0 deletions examples/worker.rb
@@ -0,0 +1,39 @@
#!/usr/bin/env ruby
#
# Worker Pool example
#
# Looking for a way to light up all your cores? This is it! Celluloid::Worker
# lets you create fixed-sized thread pools for executing expensive background
# processing tasks.

PARALLEL_RUBIES = %w(jruby rbx)

$:.push File.expand_path('../../lib', __FILE__)
require 'celluloid'
require 'digest/sha2'

class Rehasher
include Celluloid::Worker

def rehash(string, rounds)
raise ArgumentError, "hurr" unless rounds > 1
penultimate = (rounds - 1).times.inject(string) { |s| Digest::SHA512.digest(s) }
Digest::SHA512.hexdigest(penultimate)
end
end

if $0 == __FILE__
pool = Rehasher.pool
puts "Megahashing!"
if PARALLEL_RUBIES.include?(RUBY_ENGINE)
puts "Since you're using a Ruby with parallel execution, this should light up all your cores"
elsif RUBY_ENGINE == "ruby"
puts "Sorry, this Ruby interpreter has a GIL, so this will only use one core"
end

futures = %w(i am the very model of a modern major general).map do |word|
pool.future(:rehash, word, 1_000_000)
end

p futures.map(&:value)
end

0 comments on commit 73e40da

Please sign in to comment.