Skip to content

Instantly share code, notes, and snippets.

@odyss009
Last active December 13, 2016 08:14
Show Gist options
  • Save odyss009/19b39e0044565fd2d90bbfae1a047c7c to your computer and use it in GitHub Desktop.
Save odyss009/19b39e0044565fd2d90bbfae1a047c7c to your computer and use it in GitHub Desktop.
ruby multi thread 및 process test(cpu intensive job)
# test 대상 class
class Mailer
def self.deliver(&block)
mail = MailBuilder.new(&block).mail
mail.send_mail
end
Mail = Struct.new(:from, :to, :subject, :body) do
def send_mail
fib(30)
puts "Email from: #{from}"
puts "Email to : #{to}"
puts "Subject : #{subject}"
puts "Body : #{body}"
end
def fib(n)
n < 2 ? n : fib(n-1) + fib(n-2)
end
end
class MailBuilder
def initialize(&block)
@mail = Mail.new
instance_eval(&block)
end
attr_reader :mail
%w(from to subject body).each do |m|
define_method(m) do |val|
@mail.send("#{m}=", val)
end
end
end
end
#------------------------------------------------------------------------------------------------
# single - 8초 정도 소요
require 'benchmark'
require './mailer'
puts Benchmark.bm { |x|
x.report('single') do
100.times do |i|
Mailer.deliver do
from "eki_#{i}@eqbalq.com"
to "jill_#{i}@example.com"
subject "Threading and Forking (#{i})"
body "Some content"
end
end
end
}
# thread - 8초 정도 소요
require 'benchmark'
require './mailer'
puts Benchmark.bm { |x|
threads = []
x.report('thread') do
100.times do |i|
threads << Thread.new do
Mailer.deliver do
from "eki_#{i}@eqbalq.com"
to "jill_#{i}@example.com"
subject "Threading and Forking (#{i})"
body "Some content"
end
end
end
threads.map(&:join)
end
}
# process - 약 2초 정도 소요(4core)
require 'benchmark'
require './mailer'
puts Benchmark.measure{
100.times do |i|
fork do
Mailer.deliver do
from "eki_#{i}@eqbalq.com"
to "jill_#{i}@example.com"
subject "Threading and Forking (#{i})"
body "Some content"
end
end
end
Process.waitall
}
# jruby 9.1.5.0 으로 multi thread 실행시(no option) 약 3.x ~ 4.x초 정도 소요
# jruby 9.1.5.0 으로 multi thread 실행시(no option) jit 활성화 하도록 Benchmark.bmbm(두번 실행한 후 두번째 결과만을 출력) 한 경우
# 약 1.7 ~ 2초 정도 소요
require 'benchmark'
require './mailer'
puts Benchmark.bmbm { |x|
threads = []
x.report('thread') do
100.times do |i|
threads << Thread.new do
Mailer.deliver do
from "eki_#{i}@eqbalq.com"
to "jill_#{i}@example.com"
subject "Threading and Forking (#{i})"
body "Some content"
end
end
end
threads.map(&:join)
end
}
# jruby 9.1.5.0 으로 multi thread 실행시(invokeDynamic option 준 경우) -Xcompile.invokedynamic=true
# 약 0.7 ~ 0.8 초 소요
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment