On Tue, Jul 23, 2013 at 11:12 AM, Baishampayan Ghose <b.gh...@gmail.com> wrote:
> It's definitely got to do with the code, the right way to test it out
> will be to wrap the form in a function and then calling it twice. Like
> so -
>
> (time
>   (let [x (fn [] (Thread/sleep 2000)
>                    (+ 1 1))]
>          [(x) (x)]))
> ;=> "Elapsed time: 4002.0 msecs"
> ;=> [2 2]
>
> Hope that helps.
>
> Regards,
> BG
>
>
> On Tue, Jul 23, 2013 at 8:34 PM, Ryan Moore <niclas1...@gmail.com> wrote:
>> There is an example in the book The Joy of Clojure on p.262 that uses
>> futures that I evaluated in the REPL.
>>
>> user> (time
>>        (let [x (future (do (Thread/sleep 2000)
>>   (+ 1 1)))]
>> [@x @x]))
>> "Elapsed time: 2000.809 msecs"
>> [2 2]
>>
>> I figured that taking out the future would cause the execution to take twice
>> as long, however, when I try this:
>>
>> user> (time
>>        (let [x (do (Thread/sleep 2000)
>>   (+ 1 1))]
>> [x x]))
>> "Elapsed time: 2000.512 msecs"
>> [2 2]
>>
>> as you see it takes about the same amount of time. Does this have something
>> to do with the REPL evaluating things or maybe the newer version of Clojure
>> handles things differently from the Joy of Clojure book?

Can also show the difference using two different vars

  (time (let [x (future (do (Thread/sleep 2000) (+ 1 1)))
              y (future (do (Thread/sleep 3000) (+ 2 2)))]
          [@x @y]))

"Elapsed time: 3003.802 msecs"
[2 4]

  (time (let [x (do (Thread/sleep 2000) (+ 1 1))
              y (do (Thread/sleep 3000) (+ 2 2))]
          [x y]))

"Elapsed time: 5003.049 msecs"
[2 4]

Basically, [x x] doesn't do the evaluation, it happens in the let once
for x. For [@x @x] the thread is kicked off once to do the
computation, and the first @x waits for the result (if not already
available) while the second @x uses the cached value.

In my modified version, the second case the two Thread/sleep happens
in sequence, while in the first they take place in parallel thanks to
the futures.

Lars Nilsson

-- 
-- 
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/groups/opt_out.


Reply via email to