我有两个使用 Mechanize 获取 Google 索引页面的脚本。我认为 EventMachine 会比 Ruby 线程快,但事实并非如此。
EventMachine 代码成本: "0.24s user 0.08s system 2% cpu 12.682 total"
Ruby 线程代码成本: "0.22s user 0.08s system 5% cpu 5.167 total "
我是否以错误的方式使用 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
红宝石线程:
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