[plt-scheme] fibonacci number in Scheme and Ruby

From: Manfred Lotz (manfred.lotz at web.de)
Date: Tue Apr 20 14:38:14 EDT 2004

Hi there,
I compared a Ruby and a Scheme version of calculating a Fibonacci
number.

1) A non recursive Ruby version of calculating a Fibonacci number

#!/usr/local/bin/ruby
def fib(n)
  x1 = 1
  x2 = 1
  n.times do |i|
     x1, x2 = x2, x1+x2
  end
  x1 
end

N = Integer(ARGV.shift || 1)
print "Fib ", fib(N), "\n"

2) A tail recursive Scheme version of calculating a Fibonacci number.
(define (fib n)
  (let loop ((x1 1)
             (x2 1)
             (i n))
    (cond ((= i 0)
           x1)
          (else
           (loop x2 (+ x1 x2) (- i 1))))))


time ./fib1.rb 150000  
5,59s user 0,02s system 91% cpu 6,130 total

time ./fib1.scm 150000
cpu time: 22708 real time: 24866 gc time: 17871
22,75s user 0,11s system 91% cpu 25,039 total


What baffles me is that the Ruby version is so much faster than the
Scheme version. Did I do anything wrong?



-- 
Manfred


Posted on the users mailing list.