Skip to content

Instantly share code, notes, and snippets.

@ohac
Created December 6, 2009 07:44
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 ohac/250118 to your computer and use it in GitHub Desktop.
Save ohac/250118 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'drb/drb'
class MonteCarlo
def initialize(seed)
srand(seed)
end
def dice(n)
best = rand
n.times do
r = rand
best = r if r < best
end
best
end
end
PROCESSORS = (ARGV[0] || 1).to_i
pids = []
foos = PROCESSORS.times.map do |i|
uri = "druby://localhost:#{12345 + i}"
pids << fork { DRb.start_service(uri, MonteCarlo.new(i)); sleep }
DRbObject.new_with_uri(uri)
end
begin
n = 5000000 / PROCESSORS
q = Queue.new
sleep 0.1
ts = foos.map do |foo|
Thread.start(foo) {|f| q.push(f.dice(n))}
end
ts.each{|t| t.join}
p q.size.times.map{q.pop}.min
ensure
pids.each {|pid| Process.kill(:TERM, pid)}
end
# ruby1.8.7
#
# PS CoreDuo Core i7
# ------------------------
# 1 7.284s 4.482s
# 2 3.882s 2.120s
# 3 3.898s 1.417s
# 4 3.876s 1.102s
# 5 3.695s 1.163s
# 6 3.754s 0.997s
# 7 3.716s 0.958s
# 8 3.666s 0.974s
# 9 3.738s 1.029s
# 10 3.713s 0.983s
# 11 3.905s 0.981s
# 12 3.776s 0.952s
# 13 3.697s 0.934s
# ..
# 18 3.816s 0.896s
# ..
# 32 3.669s 0.907s
# ..
# 64 4.036s 0.942s
# ..
# 96 4.643s 0.973s
# ruby1.9.1
#
# PS CoreDuo Core i7
# ------------------------
# 1 4.675s 2.082s
# 2 2.677s 1.112s
# 3 2.656s 0.791s
# 4 2.609s 0.625s
# 5 2.746s 0.705s
# 6 2.649s 0.656s
# 7 2.581s 0.641s
# 8 2.626s 0.616s
# 9 2.691s 0.646s
# 10 2.617s 0.632s
# 11 2.619s 0.629s
# 12 2.573s 0.633s
# ..
# 16 2.705s 0.639s
# ..
# 32 2.619s 0.662s
# ..
# 64 3.144s 0.625s
# ..
# 96 3.010s 0.797s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment