I’m trying to add an option “message” attribute to the Clojure time macro. Basically I want to add an optional custom message to the output of time. I’m trying to find a bottleneck in my program and having some descriptive messages attached to time’s output would be very helpful.
I’ve tried the following:
;optional argument
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
[expr & msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " (first ~msg)))
ret#))
and
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
([expr] (time expr ""))
([expr msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " ~msg))
ret#)))
Both throw exceptions. How do I make this work?
It throws an exception because msg is a list,
say you call it with,
msg in the macro becomes a function call, (“asd”) which fails. Just destructure msg,
and use
You can also test how macros are expanded with macroexpand,
Also couple of points,
EDIT: time with optional message,