Skip to content

Instantly share code, notes, and snippets.

@petterik
Created January 4, 2018 23:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petterik/63fad1126842ba4550dcb338328e2975 to your computer and use it in GitHub Desktop.
Save petterik/63fad1126842ba4550dcb338328e2975 to your computer and use it in GitHub Desktop.
Benchmark code of clojure.core/some implemented with reduce and reduced
(require '[criterium.core])
(require '[clojure.pprint])
(defn some
"Returns the first logical true value of (pred x) for any x in coll,
else nil. One common idiom is to use a set as pred, for example
this will return :fred if :fred is in the sequence, otherwise nil:
(some #{:fred} coll)"
{:added "1.0"
:static true}
[pred coll]
(when (seq coll)
(or (pred (first coll)) (recur pred (next coll)))))
(defn some-2
{:static true}
[pred coll]
(reduce (fn [_ x]
(when-let [ret (pred x)]
(reduced ret)))
nil
coll))
(def i (iterate inc 0))
(def r (range 1e7))
(def v (into [] r))
(def s (doall (map inc r)))
(def st (into (sorted-set) r))
(defn benchmark-mean [benchmark]
(let [estimate (:mean benchmark)
mean (first estimate)
[factor unit] (criterium.core/scale-time mean)]
(criterium.core/format-value mean factor unit)))
(defn run-bench [dry-run?]
(let [pred #(< 1e6 %)
fns {:core-some some
:new-some some-2}
results (doall
(for [[coll-key coll] {:iterate i
:range r
:vector v
:lazy-seq s
:set st}]
(if dry-run?
(mapv #((val %) pred coll) fns)
(into {:coll coll-key}
(map (fn [[fn-key f]]
(let [mean (benchmark-mean
(criterium.core/benchmark* #(f pred coll) nil))]
[fn-key mean])))
fns))))]
(when-not dry-run?
(clojure.pprint/print-table [:coll :core-some :new-some]
results))))
(comment ;; Run through everything with a dry run to warm everything up.
(run-bench true)
;; Run everything again.
(run-bench false)
;; Prints
"|-----------+--------------+--------------|"
"| :coll | :core-some | :new-some |"
"|-----------+--------------+--------------|"
"| :iterate | 14.502145 ms | 3.994055 ms |"
"| :range | 16.949429 ms | 14.903065 ms |"
"| :vector | 23.706839 ms | 5.765865 ms |"
"| :lazy-seq | 28.723150 ms | 5.616475 ms |"
"| :set | 53.063608 ms | 17.419191 ms |"
"|-----------+--------------+--------------|"
)
(defn -main [& args]
(run-bench true)
(run-bench false))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment