A few comments:

Your two pieces of code aren't really equivalent:
a) The Python code is just calculating a fibonacci number in a brute force 
iterative loop.
b) The Clojure code is creating a big (infinite, lazy) data structure of 
all fibonacci numbers, lazily realising the structure in memory and running 
along the list until it finds the one that you want. That is a lot more 
"work"

The equivalent in Clojure to the python code would use loop / recur and 
look something like:
(defn fib
  ([n] (fib 0 1 n))
  ([a b n]
    (if (<= n 0) a
      (recur b (+' a b) (dec n)))))

Note the +' (with the tick) for arbitrary precision addition.

But mostly, I think you aren't benchmarking lazy seq performance at all: 
the dominant runtime cost of this code is almost certainly the BigInt 
addition with large numbers, not the iteration / realisation of sequences.

On Thursday, 1 January 2015 04:03:03 UTC+8, Sakis K wrote:
>
> Hi,
>
> Clojure newbie here :) I'm reading "Programming Clojure" by Halloway and 
> Bedra. In the book there is a lazy-seq example of the Fibonacci sequence:
>
> (defn lazy-seq-fibo
>   ([]
>      (concat [0 1] (lazy-seq-fibo 0N 1N)))
>   ([a b]
>      (let [n (+ a b)]      
>        (lazy-seq                       
>         (cons n (lazy-seq-fibo b n))))))
>
>
> I like the flexibility of this implementation but I am a bit sceptical 
> about its performance:
>
> user=> (time (rem (nth (lazy-seq-fibo) 1000000) 1000))
> "Elapsed time: 53552.014713 msecs"
> 875N
>
>
>
> Here's a Python implementation taken from 
> http://en.literateprograms.org/Fibonacci_numbers_%28Python%29
>
> def fib(n):
>     a, b = 0, 1
>     for i in range(n):
>         a, b = b, a + b
>     return a
>
> if __name__ == '__main__':
>     print(fib(1000000) % 1000)
>
>
> time python fib.py 
> 875
>
> real    0m16.609s
> user    0m16.475s
> sys     0m0.115s
>
>
> 53 vs 17 seconds is a big gap. Is there a way to achieve better 
> performance in Clojure? Maybe the fact that I executed the code in the REPL 
> or the Java version that I'm using matters:
> java -version
> java version "1.7.0_65"
> OpenJDK Runtime Environment (IcedTea 2.5.3) (7u71-2.5.3-0ubuntu1)
> OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)
>
>

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to