Nice!  That version runs in 6 milliseconds on my machine, fastest of
all the code posted so far.  One more idea: use 'unchecked-inc'
instead of 'unchecked-add'.  This takes it under 3 milliseconds in my
tests.

(defn java-like [^bytes cpu_array]
  (let [buffer-size (int buffer-size)]
    (loop [i (int 0)]
      (if (< i buffer-size)
        (let [i2 (unchecked-inc i)
              i3 (unchecked-inc i2)
              i4 (unchecked-inc i3)
              a (aget cpu_array i4)]
          (amove cpu_array i3 i4)
          (amove cpu_array i2 i3)
          (amove cpu_array i i2)
          (aset cpu_array i a)
          (recur (unchecked-inc i4)))))))

On Jan 30, 8:15 am, Bill James <w_a_x_...@yahoo.com> wrote:
> GrumpyLittleTed wrote:
> > Part of the difference (under 1.2) is due to the (substantial)
> > overhead of accessing the buffer-size var on every iteration.
>
> > I ran a quick check and using David's version of the code result
> > averaged 17.2ms. Just changing buffer-size to a local with using (let
> > [buffer-size (int 1920000)]...) the time dropped to an average 3.4ms.
>
> Great!  Now I remember that that same technique is used in Lua.
> See long this version takes.
>
> (set! *warn-on-reflection* true)
>
> (def buffer-size 1920000)
> (def array (byte-array buffer-size))
>
> (defmacro add [m n] `(unchecked-add (int ~m) (int ~n)))
> (defmacro amove[a i j] `(aset ~a ~j (aget ~a ~i)))
>
> (defn java-like [^bytes cpu_array]
>   (let [buffer-size (int buffer-size)]
>     (loop [i (int 0)]
>       (if (< i buffer-size)
>         (let [ i2 (add i 1)
>                i3 (add i 2)
>                i4 (add i 3)
>                a (aget cpu_array i4)
>              ]
>           (amove cpu_array i3 i4)
>           (amove cpu_array i2 i3)
>           (amove cpu_array i i2)
>           (aset cpu_array i a)
>           (recur (add i 4)))))))
>
> (dotimes [_ 10]
>   (time
>    (dotimes [_ 1]
>      (java-like array))))

-- 
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

Reply via email to