Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Worker example and parallel hash benchmark
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -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 |
This file contains 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
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -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 |