Skip to content

Instantly share code, notes, and snippets.

@ytnk531
Last active September 22, 2019 12:59
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 ytnk531/01f3f6ff1e169d6428e4cca86229743d to your computer and use it in GitHub Desktop.
Save ytnk531/01f3f6ff1e169d6428e4cca86229743d to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'concurrent'
require 'benchmark'
def api_a_call
sleep 2
'answer_from_api_a'
end
def api_b_call
sleep 4
'answer_from_api_b'
end
def compute_promise
promise = Concurrent::Promise.execute { api_a_call }
.zip(Concurrent::Promise.execute { api_b_call })
.then { |a, b| "Got: :#{a} and #{b}" }
promise.wait
end
def compute_thread
a, b = [Thread.new { api_a_call }, Thread.new { api_b_call }].map(&:value)
"Got: :#{a} and #{b}"
end
def compute_straight
a = api_a_call
b = api_b_call
"Got: :#{a} and #{b}"
end
def compute_promise_2000
promises = Array.new(2000) do
Concurrent::Promise.execute { api_a_call }
end
promises.each(&:wait)
end
def compute_thread_2000
promises = Array.new(2000) do
Thread.new { api_a_call }
end
promises.each(&:join)
end
Benchmark.bm do |b|
b.report('promise') { compute_promise }
b.report('thread') { compute_thread }
b.report('straight') { compute_straight }
b.report('promise_2000') { compute_promise_2000 }
b.report('thread_2000') { compute_thread_2000 }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment