Skip to content

Instantly share code, notes, and snippets.

@drogus
Created October 17, 2011 18:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drogus/1293386 to your computer and use it in GitHub Desktop.
Save drogus/1293386 to your computer and use it in GitHub Desktop.
persistent connections example
# This example fetches accounts of my 10 followers using Github's API
# One version uses Connection: keep-alive, the other one uses Connection: close
require 'net/https'
require 'uri'
require 'json'
require 'benchmark'
def request(uri, persistent = true)
req = Net::HTTP::Get.new uri
req.add_field 'Connection', persistent ? 'keep-alive' : 'close'
req
end
def fetch(persistent = true)
uri = URI.parse("https://api.github.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# Just for demo, don't do this at home ;)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
response = http.request( request( "/users/drogus/followers", persistent ) )
followers = JSON.parse(response.body)
followers[0..10].each do |follower|
http.request( request( follower["url"], persistent ) )
end
end
Benchmark.bm(14) do |x|
x.report("persistent ") { fetch(true) }
x.report("non-persistent") { fetch(false) }
end
user system total real
persistent 0.010000 0.000000 0.010000 ( 2.775020)
non-persistent 0.040000 0.020000 0.060000 ( 8.170520)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment