Skip to content

Instantly share code, notes, and snippets.

@AlexWayfer
Created May 1, 2017 22:06
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 AlexWayfer/e4f5ca499b346cca7bd98dd73e617928 to your computer and use it in GitHub Desktop.
Save AlexWayfer/e4f5ca499b346cca7bd98dd73e617928 to your computer and use it in GitHub Desktop.
MRI Multi-threading
# 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