Skip to content

Instantly share code, notes, and snippets.

@cameron-martin
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameron-martin/08abeaeae1bf746ef718 to your computer and use it in GitHub Desktop.
Save cameron-martin/08abeaeae1bf746ef718 to your computer and use it in GitHub Desktop.
Asynchronous vs synchronous
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
@cameron-martin
Copy link
Author

0:
       user     system      total        real
Async ordered:  0.000000   0.000000   0.000000 (  0.119964)
Async non-ordered:  0.000000   0.000000   0.000000 (  0.000108)
Sync:  0.000000   0.000000   0.000000 (  0.090405)

100000:
       user     system      total        real
Async ordered:  1.100000   0.300000   1.400000 (  1.405504)
Async non-ordered:  0.600000   0.060000   0.660000 (  0.657613)
Sync:  0.460000   0.010000   0.470000 (  0.569028)

200000:
       user     system      total        real
Async ordered:  2.250000   0.590000   2.840000 (  2.834279)
Async non-ordered:  1.340000   0.110000   1.450000 (  1.454296)
Sync:  0.720000   0.010000   0.730000 (  0.811283)

500000:
       user     system      total        real
Async ordered:  6.340000   1.810000   8.150000 (  8.198080)
Async non-ordered:  3.740000   0.430000   4.170000 (  4.169899)
Sync:  2.410000   0.150000   2.560000 (  2.666942)

1000000:
       user     system      total        real
Async ordered: 14.330000   3.380000  17.710000 ( 17.754995)
Async non-ordered:  8.400000   1.520000   9.920000 (  9.917599)
Sync:  4.920000   0.110000   5.030000 (  5.137152)

Graph: https://docs.google.com/spreadsheets/d/1zH7SQA8HBRC-WPN9s3uUr718xAvJhr2lWp7VHyx9gdU/edit?usp=sharing

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