Hello all! After reading this article: Clojure performance tips http://gnuvince.wordpress.com/2009/05/11/clojure-performance-tips/
I wrote a macro to better compare different timings of functions and expressions: (defmacro time-ms [n expr] `(let [start# (. System (nanoTime))] (dotimes [i# ~n] ~expr) (/ (double (- (. System (nanoTime)) start#)) 1000000.0))) (defmacro timings [n & expr] (let [expr-are-not-equal (cons 'not= expr) expr-times (cons 'vector (map #(list 'time-ms n %) expr))] `(if ~expr-are-not-equal (do (println "Expressions:\n") (dorun (map prn '~expr)) (println "\nare NOT equal!")) (let [~'ts ~expr-times ~'max-time (apply max ~'ts)] (dorun (map (fn [~'t ~'e] (printf "%8.2f ms %6.1f%% %5.1fx " ~'t (* 100.0 (/ ~'t ~'max-time)) (/ ~'max-time ~'t)) (prn ~'e)) ~'ts '~expr)))))) Here are the examples: (timings 1e6 (+ 2 4 5) (+ 2 (+ 4 5))) 787.96 ms 100.0% 1.0x (+ 2 4 5) 360.94 ms 45.8% 2.2x (+ 2 (+ 4 5)) ;;; (timings 1 (dotimes [i 1e6] (= i i)) (dotimes [i 1e6] (== i i))) 444.39 ms 100.0% 1.0x (dotimes [i 1000000.0] (= i i)) 237.29 ms 53.4% 1.9x (dotimes [i 1000000.0] (== i i)) (timings 1 (dotimes [i 1e6] (= i 10)) (dotimes [i 1e6] (== i 10))) 368.37 ms 100.0% 1.0x (dotimes [i 1000000.0] (= i 10)) 324.65 ms 88.1% 1.1x (dotimes [i 1000000.0] (== i 10)) ;;; (let [v [1 2 3]] (timings 1e6 (let [[a b c] v] a b c) (let [a (v 0) b (v 1) c (v 2)] a b c))) 920.15 ms 100.0% 1.0x (let [[a b c] v] a b c) 486.82 ms 52.9% 1.9x (let [a (v 0) b (v 1) c (v 2)] a b c) ;;; (def v 3) (let [l 3] (timings 1e6 v l)) 172.42 ms 100.0% 1.0x v 118.20 ms 68.6% 1.5x l ;;; (defn len [x] (.length x)) (defn len2 [#^String x] (.length x)) (def s "abcdef") (timings 1e5 (len s) (len2 s)) 1655.12 ms 100.0% 1.0x (len s) 32.82 ms 2.0% 50.4x (len2 s) Interesting is that the speed difference is smaller than in the article. Bug reports and suggestions are welcome! Frantisek --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---