public
Last active — forked from mattetti/gist:109902

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
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"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.