Skip to content

Instantly share code, notes, and snippets.

@harssh
Forked from Kukunin/ractors.rb
Created August 26, 2023 19:54
Show Gist options
  • Save harssh/9f3cf82b150841ffe3048731abafc569 to your computer and use it in GitHub Desktop.
Save harssh/9f3cf82b150841ffe3048731abafc569 to your computer and use it in GitHub Desktop.
Ruby Ractors vs Threads benchmark
require 'benchmark'
require 'etc'
Ractor.new { :warmup } if defined?(Ractor)
def fibonacci(n)
return n if (0..1).include? n
fibonacci(n - 1) + fibonacci(n - 2)
end
NUMBER = 25
TIMES = 400
CPU_CORES = 2
PER_CORE = TIMES / CPU_CORES
raise 'TIMES is not divided evenly by CPU cores' unless TIMES.modulo(CPU_CORES).zero?
Benchmark.bmbm do |x|
x.report('inline') { TIMES.times { fibonacci(NUMBER) } }
x.report('thread inline') do
Thread.new { TIMES.times { fibonacci(NUMBER) } }.join
end
x.report("threads per #{CPU_CORES} cores") do
Array.new(CPU_CORES) do
Thread.new { PER_CORE.times { fibonacci(NUMBER) } }
end.each(&:join)
end
x.report('per-task threads at once') do
Array.new(TIMES) do
Thread.new { fibonacci(NUMBER) }
end.each(&:join)
end
x.report("per-task threads batches per #{CPU_CORES} cores") do
CPU_CORES.times do
Array.new(PER_CORE) do
Thread.new { fibonacci(NUMBER) }
end.each(&:join)
end
end
if defined?(Ractor)
x.report('ractor inline') do
Ractor.new { TIMES.times { fibonacci(NUMBER) } }.take
end
x.report("ractors per #{CPU_CORES} cores") do
Array.new(CPU_CORES) do
Ractor.new { PER_CORE.times { fibonacci(NUMBER) } }
end.each(&:take)
end
x.report('per-task ractors at once') do
Array.new(TIMES) do
Ractor.new { fibonacci(NUMBER) }
end.each(&:take)
end
x.report("per-task ractor batches per #{CPU_CORES} cores") do
CPU_CORES.times do
Array.new(PER_CORE) do
Ractor.new { fibonacci(NUMBER) }
end.each(&:take)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment