[Shootout-list] Faster Ruby Fibonacci Benchmark
Jabari Zakiya
jzakiya@mail.com
Fri, 18 Mar 2005 02:18:07 -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 fib1(n-1)+ fib1(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
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.850000 0.000000 11.850000 ( 12.099299)
fib2 11.950000 0.000000 11.950000 ( 12.144117)
fib3 11.830000 0.000000 11.830000 ( 11.973985)
fib4 11.410000 0.000000 11.410000 ( 11.568537)
------------------------------------- total: 47.040000sec
user system total real
fib1 11.810000 0.000000 11.810000 ( 11.982514)
fib2 11.960000 0.000000 11.960000 ( 12.103553)
fib3 11.830000 0.000000 11.830000 ( 12.022400)
fib4 11.410000 0.000000 11.410000 ( 11.553338)
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...)
Jabari Zakiya
=3Dend
--=20
___________________________________________________________
Sign-up for Ads Free at Mail.com
http://promo.mail.com/adsfreejump.htm