Skip to content

Instantly share code, notes, and snippets.

@enforser
Last active February 25, 2021 17:53
Show Gist options
  • Save enforser/da6bc407c2e363a05d14d6baf5ad2411 to your computer and use it in GitHub Desktop.
Save enforser/da6bc407c2e363a05d14d6baf5ad2411 to your computer and use it in GitHub Desktop.
;; I use these when I want to throw a lot of `time` functions into code,
;; as it allows me to append a log to it. Using log-time-str I can
;; pass the str to whatever logging library I'm using at the time,
;; to achieve any benefits from that.
(defmacro log-time
"prints msg and the approximate number of milliseconds it took to
eval the given expression. Returns the result of the expr."
[msg expr]
`(let [start-time# (System/nanoTime)
result# ~expr
elapsed# (- (System/nanoTime) start-time#)]
(print ~msg "- Elapsed time (ms):" (/ (double elapsed#) 1000000))
result#))
;; Example
;; => (log-time "Log This!" (apply + (range 100)))
;; "Log This! - Elapsed time (ms): 0.092171
;; 4590
(defmacro log-time-str
"a wrapper around log-time to return the print as a str instead of
the result of expr. Like clojure.core/pr-str"
[& args]
`(with-out-str (log-time ~@args)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment