[Shootout-list] Correction: Faster Ruby Fibonacci Benchmark

Jabari Zakiya jzakiya@mail.com
Fri, 18 Mar 2005 02:35:10 -0500


require 'benchmark'
include Benchmark

def fib1(n) if n<2 then n else fib1(n-1)+ fib1(n-2) end end

def fib2(n) n<2 ? n : fib2(n-1)+ fib2(n-2) end

def fib3(n) if n>1 then fib3(n-1)+ fib3(n-2) else n end end

def fib4(n) n>1 ? fib4(n-1)+ fib4(n-2) : n end=20

n=3D20
bmbm(12) do |x|
  x.report("fib1") { n.times { fib1(25) } }
  x.report("fib2") { n.times { fib2(25) } }
  x.report("fib3") { n.times { fib3(25) } }
  x.report("fib4") { n.times { fib4(25) } }
end

=3Dbegin
Corrected results: fib3 was originally miswritten as
def fib3(n) if n>1 then fib1(n-1)+ fib1(n-2) else n end end
=20
The following times were generated from the above benchmark.
600Mhz Athlon K-7, 640MB, Mandrake 10.1 Official, Ruby 1.8.2

Rehearsal -----------------------------------------------
fib1         11.910000   0.010000  11.920000 ( 12.205975)
fib2         11.990000   0.000000  11.990000 ( 12.246299)
fib3         11.740000   0.000000  11.740000 ( 11.963777)
fib4         11.500000   0.000000  11.500000 ( 11.736313)
------------------------------------- total: 47.150000sec

                  user     system      total        real
fib1         11.900000   0.000000  11.900000 ( 12.133921)
fib2         12.000000   0.000000  12.000000 ( 12.248496)
fib3         11.740000   0.000000  11.740000 ( 11.955820)
fib4         11.460000   0.000000  11.460000 ( 11.696977)

fib4 is fastest, which is faster than Shootout version fib1.
Note: These versions produce the correct fibonacci sequence
for all index values n (n=3D0,1,2,3,4,5...)

=3Dend
--=20
___________________________________________________________
Sign-up for Ads Free at Mail.com
http://promo.mail.com/adsfreejump.htm