Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alazycoder101/4efc1ab4ce242583a77df61fbf14d4b0 to your computer and use it in GitHub Desktop.
Save alazycoder101/4efc1ab4ce242583a77df61fbf14d4b0 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' # gem install 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(name: 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
@alazycoder101
Copy link
Author

alazycoder101 commented Apr 27, 2023

Rehearsal -----------------------------------------------------------------
Net::HTTP::Persistent:          0.092171   0.086005   0.178176 (  0.520104)
Net::HTTP keep-alive:           0.073764   0.083357   0.157121 (  0.479915)
HttpNoTcpDelay keep-alive:      0.073535   0.084061   0.157596 (  0.472287)
Net::HTTP no keep-alive:        0.074391   0.084326   0.158717 (  0.541562)
HttpNoTcpDelay no keep-alive:   0.079566   0.093407   0.172973 (  0.479391)
-------------------------------------------------------- total: 0.824583sec

                                    user     system      total        real
Net::HTTP::Persistent:          0.095551   0.098900   0.194451 (  0.532746)
Net::HTTP keep-alive:           0.077084   0.098209   0.175293 (  0.471167)
HttpNoTcpDelay keep-alive:      0.079820   0.100471   0.180291 (  0.508415)
Net::HTTP no keep-alive:        0.081495   0.101665   0.183160 (  0.490559)
HttpNoTcpDelay no keep-alive:   0.080572   0.100381   0.180953 (  0.501883)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment