Last active
December 23, 2015 23:59
-
-
Save reborg/6713575 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; with reference to http://www.learningclojure.com/2013/09/efficiency-and-progress-my-god-clojure.html | |
(ns cljperf.core | |
(:use criterium.core)) | |
;; assumptions: we are searching for raw clojure speed for some problem | |
;; that requires just performances. We can give up some of the Clojure simplicity | |
;; and expressivness because we connected a profiler and we know what we are doing. | |
;; Second: we know how to measure. The time macro is too unreliable at this scale, | |
;; we'll use criterium. | |
(def s1 (doall (range 1000000))) | |
(def s2 (doall (range 1000000))) | |
(quick-bench (reduce + (map + s1 s2))) | |
;; Execution time mean : 317.143991 ms | |
;; Sequences that are defined in terms of car/cdr semantic and are lazy by default | |
;; are not a good candidate for speed. Prefer vectors which are still persistent | |
;; but backed by Java arrays. | |
(def v1 (vec (range 1000000))) | |
(def v2 (vec (range 1000000))) | |
(quick-bench (reduce + (map + v1 v2))) | |
;; Execution time mean : 298.012491 ms | |
;; But there are still many things going on here: | |
;; * Reflection on types | |
;; * Checked operations | |
;; * STM | |
;; It makes sense to turn all of them off at once, since in isolation | |
;; those improvements are sort of hidden. So: | |
(def a1 (int-array (range 1000000))) | |
(def a2 (int-array (range 1000000))) | |
(quick-bench (areduce ^ints a1 i ret 0 | |
(unchecked-add ret (unchecked-add | |
(aget ^ints a1 i) | |
(aget ^ints a2 i))))) | |
;; Execution time mean : 145.071658 ms | |
;; Some readeability gone, but you can pay the price for those parts | |
;; of the code where you need raw speed. Next step from here is using Java | |
;; directly (where you can have some more control over performances) or C | |
;; as you did, that probably is difficult to win. Curious to see the results on your | |
;; machine. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment