Created
October 17, 2011 18:32
-
-
Save drogus/1293386 to your computer and use it in GitHub Desktop.
persistent connections example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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