Created
November 18, 2019 23:01
-
-
Save tjstankus/172c64e45b3a9a544e6f58f619ff186b to your computer and use it in GitHub Desktop.
Fibonacci numbers in Crystal - concurrent and non-concurrent
This file contains 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
def fib(n) | |
return n if n <= 1 | |
fib(n-1) + fib(n-2) | |
end | |
###################################################### | |
# Concurrent version: | |
# $: crystal build --release fibonacci.cr | |
# $: time ./fibonacci | |
# 701408732 | |
# | |
# real 0m2.591s | |
# user 0m2.584s | |
# sys 0m0.006s | |
# channel = Channel(Int32).new | |
# sum = 0 | |
# (1..42).each do |i| | |
# spawn do | |
# channel.send(fib(i)) | |
# end | |
# sum += channel.receive | |
# end | |
# puts sum | |
###################################################### | |
# Non-concurrent version: | |
# $: crystal build --release fibonacci.cr | |
# $: time ./fibonacci | |
# 701408732 | |
# | |
# real 0m2.694s | |
# user 0m2.688s | |
# sys 0m0.005s | |
sum = 0 | |
(1..42).each do |i| | |
sum += fib(i) | |
end | |
puts sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment