Created
June 16, 2018 15:27
-
-
Save derwiki/03b22bc72c7983cd653c491567c5ea4e to your computer and use it in GitHub Desktop.
Simple script showing effective multithreading with vanilla Ruby
This file contains 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
# API endpoint that takes ~3.8s to respond | |
TARGET_URI = 'http://localhost:3000/delay' | |
SAMPLE_BODY = {} | |
def post_body! | |
Net::HTTP.post_form(TARGET_URI, SAMPLE_BODY).body | |
print ?. | |
end | |
1.upto(5).each do |concurrency| | |
threads = nil | |
Benchmark.bm do |b| | |
b.report { threads = Array.new(concurrency) { Thread.new { post_body! } }; threads.each(&:join) } | |
p "threads: #{threads.count}" | |
end | |
end | |
# $ ruby app/services/create_postcards.rb | |
# user system total real | |
# . 0.010000 0.000000 0.010000 ( 3.901472) | |
# "threads: 1" | |
# user system total real | |
# .. 0.000000 0.000000 0.000000 ( 3.866117) | |
# "threads: 2" | |
# user system total real | |
# ... 0.010000 0.000000 0.010000 ( 3.867366) | |
# "threads: 3" | |
# user system total real | |
# .... 0.010000 0.010000 0.020000 ( 3.883346) | |
# "threads: 4" | |
# user system total real | |
# ..... 0.010000 0.000000 0.010000 ( 3.885859) | |
# "threads: 5" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment