Skip to content

Instantly share code, notes, and snippets.

@beta-ziliani
Last active May 10, 2024 16:57
Show Gist options
  • Save beta-ziliani/0f815f205e7f5789fbb35653ec17d1a7 to your computer and use it in GitHub Desktop.
Save beta-ziliani/0f815f205e7f5789fbb35653ec17d1a7 to your computer and use it in GitHub Desktop.
require "benchmark"
require "big"
def fib1(n)
a = 0
b = 1
n.times { a, b = b, a + b }
a
end
def fib2(n)
a = 0
b = 1
n.times { a, b = b, a + b; nil }
a
end
def fib3(n)
a = 0
b = 1
while n > 0
a, b = b, a + b
n -= 1
end
a
end
# let's force it to not be optimized by LLVM. Thanks to @petr-fischer!
val = (ARGV[0]?.try &.to_i?) || 45
Benchmark.bm do |x|
x.report { 1_000_000.times { fib1(val) } }
x.report { 1_000_000.times { fib2(val) } }
x.report { 1_000_000.times { fib3(val) } }
end
import timeit
def fib(n):
a = 0
b = 1
while n > 0:
a, b = b, a + b
n -= 1
a
def million_fibs():
for _ in range(1000000):
fib(45)
print(timeit.timeit(lambda: million_fibs(), number=1))
require "benchmark"
def fib1(n)
a = 0
b = 1
n.times { a, b = b, a + b }
a
end
def fib2(n)
a = 0
b = 1
n.times { a, b = b, a + b; nil }
a
end
def fib3(n)
a = 0
b = 1
while n > 0
a, b = b, a + b
n -= 1
end
a
end
Benchmark.bm do |x|
x.report { 1_000_000.times { fib1(45) } }
x.report { 1_000_000.times { fib2(45) } }
x.report { 1_000_000.times { fib3(45) } }
end
@JobLeonard
Copy link

Ehm, you're calling fib on a constant number. Isn't Crystal capable of doing compile-time evaluation on constants, meaning it doesn't do any run-time calculations?

@petr-fischer
Copy link

I tried to modify it and parse fib argument from ARGV command line like this:

# ...
val = ARGV[0].to_i
puts val

Benchmark.bm do |x|
  x.report { a = 0_u128; 1_000_000.times { a += fib1(val) }; puts a }
  x.report { a = 0_u128; 1_000_000.times { a += fib2(val) }; puts a }
  x.report { a = 0_u128; 1_000_000.times { a += fib3(val) }; puts a }
end

and now it's at least 10x slower.

@beta-ziliani
Copy link
Author

beta-ziliani commented May 10, 2024

Thanks! I edited the post (and the code) accordingly.

tl;dr: points stand still.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment