diff --git a/common/src/app/common/perf.cljc b/common/src/app/common/perf.cljc index ca235835b6..454ab3f6b4 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})))) +