Created
October 15, 2012 12:03
-
-
Save redsquirrel/3892119 to your computer and use it in GitHub Desktop.
This file contains hidden or 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_recursive(i, m = 0, n = 1, count = 0) | |
| return m if count == i | |
| fib_recursive(i, n, m+n, count+1) | |
| end | |
| def fib_iterative(i) | |
| m, n = 0, 1 | |
| i.times do | |
| m, n = n, m+n | |
| end | |
| m | |
| end |
require 'benchmark'
ITERATIONS = ARGV.fetch(0) { 100 }.to_i
Benchmark.bmbm do |x|
x.report('fib_recursive') do
ITERATIONS.times { fib_recursive(1000) }
end
x.report('fib_iterative') do
ITERATIONS.times { fib_iterative(1000) }
end
x.report('fib_ewd') do
ITERATIONS.times { fib_ewd(1000) }
end
endjesse@thorin ~/code/scratch $ ruby fib_bench.rb 1000
Rehearsal -------------------------------------------------
fib_recursive 0.900000 0.000000 0.900000 ( 0.901630)
fib_iterative 1.220000 0.000000 1.220000 ( 1.218426)
fib_ewd 0.090000 0.000000 0.090000 ( 0.091430)
---------------------------------------- total: 2.210000sec
user system total real
fib_recursive 0.890000 0.000000 0.890000 ( 0.891279)
fib_iterative 1.210000 0.000000 1.210000 ( 1.215739)
fib_ewd 0.090000 0.000000 0.090000 ( 0.089533)
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

I FIGHT YOU