Skip to content

Instantly share code, notes, and snippets.

@rhishikeshj
Created August 23, 2023 11:06
Show Gist options
  • Save rhishikeshj/3039213fcd6dd89e43d7850feceae9e6 to your computer and use it in GitHub Desktop.
Save rhishikeshj/3039213fcd6dd89e43d7850feceae9e6 to your computer and use it in GitHub Desktop.
A more flexible version of the `clojure.core/time` function
(defmacro record-time
"Evaluates expr and calls recorder fn. Returns value of expr.
recorder is an fn of 2 args,
time-taken double
expr string"
[recorder expr]
`(let [start# (. System (nanoTime))
ret# ~expr]
(~recorder (/ (double (- (. System (nanoTime)) start#)) 1000000.0) ~(str expr))
ret#))
(defmacro log-time
"Evaluates expr and logs time it took.
Returns the value of expr."
[expr]
`(record-time #(log/trace {:tt %1 :expr %2}) ~expr))
;; Usage
(common/log-time (do (Thread/sleep 1000) :ok))
=> {"timestamp":"2023-08-23T11:05:55.518Z","level":"ERROR","thread":"nREPL-session-ca6d8d4a-dacc-4de0-ae8a-484e6a43a046","ns":"\"user\"","logger":"user","message":"{:tt 1008.649625, :expr \"(do (Thread/sleep 1000) :ok)\"}","context":"default"}
=> :ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment