Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Last active December 28, 2023 12:53
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Kukunin/960ccef0d3c0a2c4b28ff5345911c2a5 to your computer and use it in GitHub Desktop.
Save Kukunin/960ccef0d3c0a2c4b28ff5345911c2a5 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
@Kukunin
Copy link
Author

Kukunin commented Apr 25, 2021

The easiest way for you to understand ractors is that Ractor.new == Thread.new, but running with more limitations (no shared objects) and in a truly parallel manner. Not more (at least for now)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment