Skip to content

Instantly share code, notes, and snippets.

@nathanl
Created July 27, 2017 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanl/ae33fd6bcf14a96bc1fe9df456c4f210 to your computer and use it in GitHub Desktop.
Save nathanl/ae33fd6bcf14a96bc1fe9df456c4f210 to your computer and use it in GitHub Desktop.
Ruby threads - not useless! They can help with IO.
10 requests with no threads
response codes: ["200", "200", "200", "200", "200", "200", "200", "200", "200", "200"]
that took 1.787615 seconds
10 requests with threads
response codes: ["200", "200", "200", "200", "200", "200", "200", "200", "200", "200"]
that took 0.200502 seconds
# Shows that, for IO operations like HTTP requests, Ruby does actually benefit
# from multithreading.
#
# The GIL means that only one thing executes on the CPU at a time, but it
# doesn't prevent us from running a different thread while one thread is
# waiting on IO (like an HTTP response)
require "net/http"
require "uri"
require "time"
uri = URI.parse("http://nathanmlong.com")
n = 10
puts "#{n} requests with no threads"
start_time = Time.now
response_codes = n.times.map {
Net::HTTP.get_response(uri)
}.map {|response| response.code}
end_time = Time.now
puts "response codes: #{response_codes}"
puts "that took #{end_time - start_time} seconds"
puts
puts "#{n} requests with threads"
start_time = Time.now
response_codes = n.times.map {
Thread.new { Net::HTTP.get_response(uri) }
}.map {|thread|
thread.value
}.map {|response| response.code}
end_time = Time.now
puts "response codes: #{response_codes}"
puts "that took #{end_time - start_time} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment