Last active
May 10, 2024 16:57
-
-
Save beta-ziliani/0f815f205e7f5789fbb35653ec17d1a7 to your computer and use it in GitHub Desktop.
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
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 | |
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
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)) |
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
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 |
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.
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
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?