Created
July 27, 2017 16:23
-
-
Save nathanl/ae33fd6bcf14a96bc1fe9df456c4f210 to your computer and use it in GitHub Desktop.
Ruby threads - not useless! They can help with IO.
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
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 |
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
# 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