Skip to content

Instantly share code, notes, and snippets.

@tjstankus
Created November 18, 2019 23:01
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 tjstankus/172c64e45b3a9a544e6f58f619ff186b to your computer and use it in GitHub Desktop.
Save tjstankus/172c64e45b3a9a544e6f58f619ff186b to your computer and use it in GitHub Desktop.
Fibonacci numbers in Crystal - concurrent and non-concurrent
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