Skip to content

Instantly share code, notes, and snippets.

@dylanahsmith
Created January 9, 2014 23:04
Show Gist options
  • Save dylanahsmith/8343785 to your computer and use it in GitHub Desktop.
Save dylanahsmith/8343785 to your computer and use it in GitHub Desktop.
Benchmarking Net::HTTP with and without keep-alive and TCP_NODELAY
#!/usr/bin/env ruby
require 'net/http'
require 'net/http/persistent'
require 'benchmark'
class HttpNoTcpDelay < Net::HTTP
def on_connect
@socket.io.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
nil
end
end
ES_URI = URI("http://localhost:9200/")
ES_REQUEST = Net::HTTP::Get.new(ES_URI)
CONNECTION_NAME = "elasticsearch"
def net_http_persistent_test(n)
http = Net::HTTP::Persistent.new(CONNECTION_NAME)
n.times do
http.request(ES_URI, ES_REQUEST)
end
end
def net_http_test(http_class, keep_alive, n)
http = http_class.new(ES_URI.host, ES_URI.port)
if keep_alive
http.keep_alive_timeout = 60
http.start
end
n.times do
http.request(ES_REQUEST)
end
end
ITERATIONS = 1000
Benchmark.bmbm do |x|
x.report("Net::HTTP::Persistent:") { net_http_persistent_test(ITERATIONS) }
x.report("Net::HTTP keep-alive:") { net_http_test(Net::HTTP, true, ITERATIONS) }
x.report("HttpNoTcpDelay keep-alive:") { net_http_test(HttpNoTcpDelay, true, ITERATIONS) }
x.report("Net::HTTP no keep-alive:") { net_http_test(Net::HTTP, false, ITERATIONS) }
x.report("HttpNoTcpDelay no keep-alive:") { net_http_test(HttpNoTcpDelay, false, ITERATIONS) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment