So I was wrote a function that read a InputStream into a
FileOutputStream.
I noticed (after my CPU fan kept turning on) that it was taking
upwards of 70% of my Athlon 64 X2 +5000!
Heres that version:

(defn read-bytes-to-file [istream filename]
  (with-open [ostream (new FileOutputStream filename)]
    (let [buffer (make-array (. Byte TYPE) 4096)]
      (loop [b-read (. istream (read buffer))]
        (if (neg? b-read)
          nil
          (do (.write ostream buffer 0 b-read)
              (recur (.read istream))))))))

user> (time-test (read-bytes-to-file (.openStream (new URL "http://
imgs.xkcd.com/comics/google_trends.png")) "/dev/null"))
"Elapsed time: 1183.442361 msecs"
"Elapsed time: 533.216065 msecs"
"Elapsed time: 502.899459 msecs"
"Elapsed time: 499.715278 msecs"
"Elapsed time: 505.39608 msecs"
nil

This version is actually the result of me messing around with it for a
while (Trying Buffering and such).
Then I read a post here and tried this:

(defn read-bytes-to-file [istream filename]
  (with-open [ostream (new FileOutputStream filename)]
    (let [buffer (make-array (. Byte TYPE) 4096)]
      (loop [b-read (. istream (read buffer))]
        (if (pos? b-read)
          (do (.write ostream buffer 0 b-read)
              (recur (.read istream)))
          nil)))))

and got this:

(time-test (read-bytes-to-file (.openStream (new URL "http://
imgs.xkcd.com/comics/google_trends.png")) "/dev/null"))
"Elapsed time: 423.394728 msecs"
"Elapsed time: 186.605035 msecs"
"Elapsed time: 201.295071 msecs"
"Elapsed time: 201.775338 msecs"
"Elapsed time: 197.739148 msecs"
nil

It also only uses up to 2 percent of the CPU. So I guess its really
important to make the then of an if the most likely case. Anybody know
why?

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to