Skip to content

Instantly share code, notes, and snippets.

@jcasts
Created September 26, 2011 17:38
Show Gist options
  • Save jcasts/1242830 to your computer and use it in GitHub Desktop.
Save jcasts/1242830 to your computer and use it in GitHub Desktop.
Simple synchronous benchmarking of em-http-request net/http and httpclient
require 'rubygems'
require 'net/http'
require 'httpclient'
require 'eventmachine'
require 'em-http'
num = ARGV[0] || 1000
url = "http://localhost:8080"
uri = URI.parse url
def timer
s = Time.now
yield
Time.now - s
end
def benchmark num
avg = 0
i = 0
while i < num
time = timer do
yield
end
if time.to_i > 5 && i == 0
puts "not recording first slow connection: #{time.to_f * 1000}"
next
end
avg = ((avg * i) + time) / (i+1)
i += 1
$stdout << "."
$stdout.flush
end
puts "\n"
avg.to_f * 1000
end
class EMBench
class << self
attr_accessor :avg, :count
end
@avg = 0
@count = 0
def count
self.class.count
end
def count= value
self.class.count = value
end
def avg
self.class.avg
end
def avg= value
self.class.avg = value
end
def request client, head, body
@start = Time.now
[head, body]
end
def response resp
time = Time.now - @start
if time.to_i > 5 && self.count == 0
puts "not recording first slow connection: #{time.to_f * 1000}"
return resp
end
self.avg = ((self.avg * self.count) + time) / (self.count+1)
self.count += 1
$stdout << "."
#$stdout << "#{time}\n"
$stdout.flush
resp
end
end
def em_bench uri, num
http = EM::HttpRequest.new(uri)
http.use EMBench
http.get.callback do
if EMBench.count >= num
EM.stop
else
em_bench uri, num
end
end
end
def bench_eventmachine uri, num
puts "benchmarking EM #{num} times"
EM::run do
em_bench uri, num
end
puts "\n"
EMBench.avg = EMBench.avg.to_f * 1000
"eventmachine avg: #{EMBench.avg}"
end
def bench_nethttp uri, num
puts "benchmarking net/http #{num} times"
net_clnt = Net::HTTP.new(uri.host, uri.port).start
get_req = Net::HTTP::Post.new "/"
net_res = benchmark num do
net_clnt.request get_req
end
net_clnt.finish
"net/http avg: #{net_res}"
end
def bench_httpclient uri, num
puts "benchmarking httpclient #{num} times"
gem_clnt = HTTPClient.new
gem_res = benchmark num do
gem_clnt.post uri
end
"httpclient avg: #{gem_res}"
end
res = []
trap 'INT' do
puts res.join("\n")
end
res << bench_eventmachine(uri, num)
res << bench_nethttp(uri, num)
res << bench_httpclient(uri, num)
puts res.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment