Why Eventmachine Defer slower than Ruby Thread?

Posted by allenwei on Stack Overflow See other posts from Stack Overflow or by allenwei
Published on 2010-06-17T23:34:11Z Indexed on 2010/06/17 23:43 UTC
Read the original article Hit count: 291

Filed under:
|

I have two scripts which using mechanize to fetch google index page. I assuming Eventmachine will faster than ruby thread, but not.

Eventmachine code cost "0.24s user 0.08s system 2% cpu 12.682 total" Ruby Thread code cost "0.22s user 0.08s system 5% cpu 5.167 total "

Am I use eventmachine in wrong way?

Who can explain it to me, thanks!

1 Eventmachine

require 'rubygems'
require 'mechanize'
require 'eventmachine'

trap("INT") {EM.stop}

EM.run do 
  num = 0
  operation = proc {
    agent = Mechanize.new
    sleep 1
    agent.get("http://google.com").body.to_s.size
  }
  callback = proc { |result|
    sleep 1
    puts result
    num+=1
    EM.stop if num == 9
  }

  10.times do 
    EventMachine.defer operation, callback
  end
end

2 Ruby Thread

require 'rubygems'
require 'mechanize'


threads = []
10.times do 
  threads << Thread.new do 
    agent = Mechanize.new
    sleep 1
    puts agent.get("http://google.com").body.to_s.size
    sleep 1
  end
end


threads.each do |aThread| 
  aThread.join
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about eventmachine