Skip to content

Instantly share code, notes, and snippets.

@tsdh
Created February 28, 2012 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsdh/1932917 to your computer and use it in GitHub Desktop.
Save tsdh/1932917 to your computer and use it in GitHub Desktop.
(defmacro timing
"Times the execution of `form' and returns its result.
Additionally, prints (format fmt args), where two new formatters are
available:
%T: the timing information (e.g., 1.71827 msecs)
%R: the result of evaluating `expr'
%F: the input form that is timed
Example:
user> (timing \"%s It took %T to eval %F to %R.\" (take 10 (iterate inc 0)) \";\")
; It took 0.031708 msecs to eval (take 10 (iterate inc 0)) to (0 1 2 3 4 5 6 7 8 9).
(0 1 2 3 4 5 6 7 8 9)"
[fmt form & args]
`(let [p# (promise)
tstr# (-> (with-out-str
(deliver p# (time ~form)))
(str/replace "Elapsed time: " "")
(str/replace "\"" "")
(str/trim-newline))]
(println (format (-> ~fmt
(str/replace "%T" tstr#)
(str/replace "%R" (print-str @p#))
(str/replace "%F" (print-str (quote ~form))))
~@args))
@p#))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment