Last active
August 29, 2015 14:05
-
-
Save cameron-martin/08abeaeae1bf746ef718 to your computer and use it in GitHub Desktop.
Asynchronous vs synchronous
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'eventmachine' | |
require 'benchmark' | |
rand_iterations = 10 | |
define_method(:generate_func) do | |
# This is so we have n different function objects, which seems more realistic | |
proc { rand_iterations.times { rand(0..10) } } | |
end | |
[0, 100_000, 200_000, 500_000, 1_000_000].each do |n| | |
puts "#{n}:\n" | |
Benchmark.bm do |x| | |
x.report("Async ordered:") do | |
EM.run do | |
n.times.map { generate_func }.inject(proc{ EM.stop }) do |memo, func| | |
proc { EM.next_tick { func.call; memo.call } } | |
end.call | |
end | |
end | |
x.report("Async non-ordered:") do | |
EM.run do | |
n.times.map { generate_func }.each do |func| | |
EM.next_tick { func.call } | |
end | |
EM.next_tick { EM.stop } # Does this guarantee to run the above functions first? | |
end | |
end | |
x.report('Sync:') do | |
EM.run do | |
n.times.map { generate_func }.each { |func| func.call } | |
EM.stop | |
end | |
end | |
end | |
puts "\n" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Graph: https://docs.google.com/spreadsheets/d/1zH7SQA8HBRC-WPN9s3uUr718xAvJhr2lWp7VHyx9gdU/edit?usp=sharing