Skip to content

Instantly share code, notes, and snippets.

@chris-arsenault
Created October 26, 2017 18:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-arsenault/d14f0c1f535b4f43519f686d6bd66813 to your computer and use it in GitHub Desktop.
Save chris-arsenault/d14f0c1f535b4f43519f686d6bd66813 to your computer and use it in GitHub Desktop.
Shows how different ruby concurrency models operate
puts "Runnin those tests"
NUM_ARRAYS = 1600
ARRAY_SIZE = 16000
NUM_THREADS = 4
start = Time.now
sortables = Array.new(NUM_ARRAYS) { Array.new(ARRAY_SIZE) { rand(1...ARRAY_SIZE) } }
processes_sortables = []
sortables.each do |s|
processes_sortables << s.dup
end
threads_sortables = []
sortables.each do |s|
threads_sortables << s.dup
end
fibers_sortables = []
sortables.each do |s|
fibers_sortables << s.dup
end
puts "I did arrays in #{(Time.now - start)*1000}"
start = Time.now
sortables.each do |sort_me|
sort_me.sort!
end
puts "I sorted the arrays with no concurrency in #{(Time.now - start)*1000} ms"
start = Time.now
processes_sortables.each_slice(NUM_ARRAYS/NUM_THREADS) do |slice|
fork {
s = Time.now
puts slice.size
slice.each do |arr|
arr.sort!
end
puts "Fork done #{Time.now - s}"
}
end
Process.waitall
puts "I sorted the arrays with processes in #{(Time.now - start)*1000} ms"
start = Time.now
threads = []
threads_sortables.each_slice(NUM_ARRAYS/NUM_THREADS) do |slice|
threads << Thread.new {
s = Time.now
puts slice.size
slice.each do |arr|
arr.sort!
end
puts "Thread done #{Time.now - s}"
}
end
threads.each do |t|
t.join
end
puts "I sorted the arrays with threads in #{(Time.now - start)*1000} ms"
start = Time.now
fibers = []
fibers_sortables.each_slice(NUM_ARRAYS/NUM_THREADS) do |slice|
fibers << Fiber.new {
s = Time.now
puts slice.size
slice.each do |arr|
arr.sort!
end
puts "Fiber done #{Time.now - s}"
}
end
fibers.each do |f|
f.resume
end
puts "I sorted the arrays with fibers in #{(Time.now - start)*1000} ms"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment