From 73042115e017a49cdbafe045dde37636f886f174 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Fri, 3 Dec 2021 09:30:33 +0100 Subject: [PATCH] :tada: Add `benchmark` helper function (cljs only). --- common/src/app/common/perf.cljc | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/common/src/app/common/perf.cljc b/common/src/app/common/perf.cljc index ca235835b..454ab3f6b 100644 --- a/common/src/app/common/perf.cljc +++ b/common/src/app/common/perf.cljc @@ -19,3 +19,34 @@ (defn measure [key] (- (timestamp) (get @measures key))) + +#?(:cljs + (defn benchmark + "A helper function for perform a unitari benchmark on JS/CLJS. It + uses browser native api so it only suitable to be executed in + browser." + [& {:keys [f warmup iterations name] + :or {iterations 10000}}] + (let [end-mark (str name ":end")] + (println "=> benchmarking:" name) + (println "--> warming up:" iterations) + (loop [i iterations] + (when (pos? i) + (f) + (recur (dec i)))) + (println "--> benchmarking:" iterations) + (js/performance.mark name) + (loop [i iterations] + (when (pos? i) + (f) + (recur (dec i)))) + (js/performance.measure end-mark name) + (let [[result] (js/performance.getEntriesByName end-mark) + duration (mth/precision (.-duration ^js result) 6) + avg (mth/precision (/ duration iterations) 6)] + (println "--> TOTAL:" (str duration "ms") "AVG:" (str avg "ms")) + (js/performance.clearMarks name) + (js/performance.clearMeasures end-mark) + #js {:duration duration + :avg avg})))) +