Skip to content

Instantly share code, notes, and snippets.

@odyss009
Last active December 13, 2016 09:00
Show Gist options
  • Save odyss009/b8796c17022ead28efe83c9fdaf2664f to your computer and use it in GitHub Desktop.
Save odyss009/b8796c17022ead28efe83c9fdaf2664f to your computer and use it in GitHub Desktop.
ruby I/O multi test
# sinatra
require 'sinatra'
require 'json'
get '/' do
'Hello sinatra'
end
get '/api/v2/users/:user_id/subscriptions' do
user_id = params['user_id']
puts "get subscription #{user_id}"
sleep 1
hash = { subscriptions: user_id }
hash.to_json
end
get '/api/v2/users/:user_id/recents' do
user_id = params['user_id']
puts "get recents #{user_id}"
sleep 1
hash = { recents: user_id }
hash.to_json
end
#-----------------------------------------------------
# test
require 'faraday'
require 'faraday_middleware'
require 'typhoeus/adapters/faraday'
require 'multi_json'
require 'benchmark'
header_option = {}
host = 'http://localhost:4567/api/'
typhoeus_conn = Faraday.new(:url => host, headers: header_option) do |faraday|
faraday.request :json # json request
faraday.response :json, content_type: /\bjson$/
faraday.adapter :typhoeus # make requests with Net::HTTP
end
user_ids = %w(1 2 3 4 5 6 7 8 9 10)
def mass_serial_request(conn, user_ids)
responses = []
user_ids.each_with_index do |user_id, index|
responses << conn.get("v2/users/#{user_id}/subscriptions").body
responses << conn.get("v2/users/#{user_id}/recents").body
end
end
def serial_request(conn, user_id)
#response1 = conn.get "v1/users/#{user_id}"
response2 = conn.get "v2/users/#{user_id}/subscriptions"
response3 = conn.get "v2/users/#{user_id}/recents"
end
def threaded_request(conn, user_ids, block)
threads = []
user_ids.each_with_index do |user_id, index|
threads << Thread.new { block.call(conn, user_id) }
end
threads.each(&:join)
end
def mass_parallel_request(conn, user_ids)
responses = []
conn.in_parallel do
user_ids.each do |user_id|
responses << conn.get("v2/users/#{user_id}/subscriptions")
responses << conn.get("v2/users/#{user_id}/recents")
end
end
end
# single test - 20초 정도 소요
puts Benchmark.measure { mass_serial_request(http_persistent_conn, user_ids) }
# multi thread test 약 2초 소요
puts Benchmark.measure { threaded_request(typhoeus_conn, user_ids, lambda(&method(:serial_request))) }
# typhoeus의 parallel을 이용한 test - typhoeus gem(libcurl에 의존 - c extension)이 자체적으로 parallel을 지원: 약 1초 정도 소요
puts Benchmark.measure { mass_parallel_request(typhoeus_conn, user_ids) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment