Permalink
Browse files

Worker example and parallel hash benchmark

  • Loading branch information...
1 parent 19739fb commit 73e40da2e20d5731f4ec2bf39590712127151f43 @tarcieri tarcieri committed Apr 9, 2012
Showing with 54 additions and 0 deletions.
  1. +15 −0 benchmarks/parallel_hash.rb
  2. +39 −0 examples/worker.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
View
@@ -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.