Created
May 1, 2017 22:06
-
-
Save AlexWayfer/e4f5ca499b346cca7bd98dd73e617928 to your computer and use it in GitHub Desktop.
MRI Multi-threading
This file contains hidden or 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 | |
def fibonacci(n) | |
return n if n <= 1 | |
fibonacci(n - 1) + fibonacci(n - 2) | |
end | |
def calculate(id: 1, n: 40) | |
start = Time.now | |
puts "Start ##{id}: #{start}" | |
puts fibonacci(n) | |
finish = Time.now | |
puts "Finish ##{id}: #{finish} (#{finish - start} seconds)" | |
end | |
puts 'One thread:' | |
calculate id: 0 | |
puts 'Two threads:' | |
threads = 2.times.with_object([]) do |i, arr| | |
arr << Thread.new { calculate id: i + 1 } | |
end | |
threads.each(&:join) | |
# $ ruby fibonacci.rb | |
# One thread: | |
# Start #0: 2017-05-02 01:05:14 +0300 | |
# 102334155 | |
# Finish #0: 2017-05-02 01:05:24 +0300 (9.72420595 seconds) | |
# Two threads: | |
# Start #1: 2017-05-02 01:05:24 +0300 | |
# Start #2: 2017-05-02 01:05:24 +0300 | |
# 102334155 | |
# Finish #1: 2017-05-02 01:05:43 +0300 (18.78237694 seconds) | |
# 102334155 | |
# Finish #2: 2017-05-02 01:05:43 +0300 (19.151724752 seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment