Last active
September 22, 2019 12:59
-
-
Save ytnk531/01f3f6ff1e169d6428e4cca86229743d to your computer and use it in GitHub Desktop.
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
# 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