Skip to content

Instantly share code, notes, and snippets.

@derwiki
Created June 16, 2018 15:27
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 derwiki/03b22bc72c7983cd653c491567c5ea4e to your computer and use it in GitHub Desktop.
Save derwiki/03b22bc72c7983cd653c491567c5ea4e to your computer and use it in GitHub Desktop.
Simple script showing effective multithreading with vanilla Ruby
# 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