Skip to content

Instantly share code, notes, and snippets.

@francisco-rojas
Forked from Kukunin/ractors.rb
Created September 19, 2025 18:44
Show Gist options
  • Save francisco-rojas/78ee8683a45179e1ef66e112bfb5c520 to your computer and use it in GitHub Desktop.
Save francisco-rojas/78ee8683a45179e1ef66e112bfb5c520 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