Skip to content

Instantly share code, notes, and snippets.

@pauldix
Forked from mattetti/gist:109902
Created May 13, 2009 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pauldix/111223 to your computer and use it in GitHub Desktop.
Save pauldix/111223 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'json'
require 'typhoeus'
require 'net/http'
class CouchDB
include Typhoeus
remote_defaults :on_success => lambda {|response| JSON.parse(response.body)},
:on_failure => lambda {|response| puts "error code: #{response.code}"},
:base_uri => "http://127.0.0.1:5984/couch-test-db"
define_remote_method :doc, :path => '/document-id'
end
# Matt's previous example wasn't quite using Typhoeus correctly. It was making the requests
# serially. Instead, put the objects returned by the remote_method calls into an array.
# Then do something with them. All the remote_method calls will then be made at that point in
# parallel. It's the whole lazy evaluation thing. Matt's example was forcing evaluation after each.
tstart_time = Time.now
docs = []
100.times do |i|
# need to toss in a garbage param so Typhoeus doesn't memoize and only make 1 request
docs << CouchDB.doc(:params => {:whatev => i})
end
docs.each {|d| p doc.to_s.to_f} # on the first doc is when the actual calls are made
# there's one other thing I forgot to mention. Typhoeus keeps a pool of libcurl easy handles to
# run requests. Warming the pool can take a little extra time. In the grand scheme of things this
# doesn't matter. For a benchmark, however, the pool should really be warmed before starting
# measurements.
puts "sleep 45s"
sleep 45
docs = []
100.times do |i|
# need to toss in a garbage param so Typhoeus doesn't memoize and only make 1 request
docs << CouchDB.doc(:params => {:whatev => i})
end
docs.each {|d| p doc.to_s.to_f} # on the first doc is when the actual calls are made
ttime = Time.now - tstart_time
nstart_time = Time.now
def connection
Net::HTTP.new("127.0.0.1", 5984)
end
def request
@request ||= Proc.new { @http.request(Net::HTTP::Get.new("/couch-test-db/document-id")) }
end
@net = connection
@http = @net.start
def get_doc
begin
res = request.call
rescue Errno::ECONNRESET
p "rescue"
@net = connection
@http = @net.start
res = request.call
end
p JSON.parse(res.body).to_s.to_f
end
100.times do
get_doc
end
puts 'sleep 45s'
# forcing a connection error rescue
sleep 45
100.times do
get_doc
end
etime = Time.now - nstart_time
p "typhoeus total time: #{ttime}"
p "net/http total time: #{etime}"
p "net/http was #{etime - ttime}s faster/slower"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment