Skip to content

Instantly share code, notes, and snippets.

@aria42
Last active December 14, 2015 04:09
Show Gist options
  • Save aria42/5026109 to your computer and use it in GitHub Desktop.
Save aria42/5026109 to your computer and use it in GitHub Desktop.
(ns speed-test.core
;; Original Java Source
(:import LCS))
(set! *warn-on-reflection* true)
(defn time-it [num-trials f]
(loop [sum-ms 0 trials-left num-trials]
(let [start (System/currentTimeMillis)]
(f)
(let [stop (System/currentTimeMillis)
ms (- stop start)]
(if (>= trials-left 0)
(recur (+ sum-ms ms) (dec trials-left))
(double (/ (+ sum-ms ms) num-trials 1000.0)))))))
(defmacro arr-max
"return maximum value of `expr` over the indices
and values of array `arr`, where `idx-symb` and `val-symb`
are bound to index and values of `arr`"
[arr idx-symb val-symb expr]
`(let [arr# ~arr
n# (alength arr#)]
(loop [~idx-symb 0 max-val# java.lang.Long/MIN_VALUE]
(if (= ~idx-symb n#)
max-val#
(let [~val-symb (aget arr# ~idx-symb)
val# ~expr]
(recur (inc ~idx-symb)
(if (> val# max-val#)
val# max-val#)))))))
(defn lcs [^objects a1 ^objects a2]
(let [prev-ref (atom (long-array (inc (alength a2))))
cur-ref (atom (long-array (inc (alength a2))))]
(arr-max a1 i v1
(let [^longs prev @prev-ref
^longs cur @cur-ref
max-len (arr-max a2 j v2
(let [match-len (if (.equals v1 v2)
(inc (aget prev j))
0)]
(aset cur (inc j) match-len)
match-len))]
(reset! prev-ref cur)
(reset! cur-ref prev)
(long max-len)))))
(defn -main [& _]
(let [pool "ABC"
get-random-id (fn[n] (apply str (repeatedly n #(rand-nth pool))))
^objects a1 (into-array (take 10000 (repeatedly #(get-random-id 5))))
^objects a2 (into-array (take 10000 (repeatedly #(get-random-id 5))))]
;;0.79052 secs
(println "Avg time for java " (time-it 25 #(LCS/lcs a1 a2)) "secs")
;;1.18824 secs
(println "Avg time for clojure " (time-it 25 #(lcs a1 a2)) "secs")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment