我正在尝试向Clojure时间宏添加一个选项“message”属性。基本上我想在时间输出中添加一个可选的自定义消息。我试图找到我的程序中的瓶颈,并且在时间输出上附加一些描述性消息会非常有用。
我尝试了以下内容:
;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#))
和
(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#)))
两者都抛出异常。我如何使这项工作?
答案 0 :(得分:4)
它会引发异常,因为msg是一个列表,
说你打电话给,
(time (+ 1 1) "asd")
宏中的msg变为函数调用(“asd”)失败。只是构建消息,
[expr & [msg]]
并使用
~msg
您还可以使用macroexpand测试宏的扩展方式,
(macroexpand '(time (+ 1 1) "asd"))
还有几点,
编辑:时间与可选消息,
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
[expr & [msg]]
(let [msg (if (nil? msg) "" msg)]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " ~msg))
ret#)))
(time (+ 1 1))
"Elapsed time: 0.068 msecs. "
2
(time (+ 1 1) "asd")
"Elapsed time: 0.067 msecs. asd"
2