Skip to content

Instantly share code, notes, and snippets.

@ytnk531
Created September 22, 2019 13:00
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/3bc46e375b7189cd32f6ba97149d8805 to your computer and use it in GitHub Desktop.
Save ytnk531/3bc46e375b7189cd32f6ba97149d8805 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
@ytnk531
Copy link
Author

ytnk531 commented Sep 22, 2019

Result.

       user     system      total        real
promise  0.000000   0.000000   0.000000 (  4.003213)
thread  0.015625   0.000000   0.015625 (  4.001636)
straight  0.000000   0.000000   0.000000 (  6.003344)
promise_2000  1.015625   1.656250   2.671875 (  5.090374)
thread_2000  1.171875   3.375000   4.546875 (  6.612067)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment