ClojureDocs

Nav

Namespaces

time

clojure.core

Available since 1.0 (source)
  • (time expr)
Evaluates expr and prints the time it took.  Returns the value of
 expr.
5 Examples
user> (time (Thread/sleep 100))
"Elapsed time: 100.284772 msecs"
nil
;when working with lazy seqs
(time (doall (...)))
;; Time how long it takes to write a string to a file 100 times
(defn time-test []
  (with-open [w (writer "test.txt" :append false)]
    (dotimes [_ 100]
      (.write w "I am being written to a file."))))


user=> (time (time-test))
"Elapsed time: 19.596371 msecs"
user=> (time (Thread/sleep 1000))
"Elapsed time: 1000.267483 msecs"
nil
user=> (with-out-str (time (Thread/sleep 1000)))
"\"Elapsed time: 1010.12942 msecs\"\n"

;;get elapsed time in seconds:

(defmacro sectime
  [expr]
  `(let [start# (. System (currentTimeMillis))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (currentTimeMillis)) start#)) 1000.0) " secs"))
     ret#))
See Also
No see-alsos for clojure.core/time
1 Note
    By , created 3.1 years ago

    Because the Java JIT compiler compiles code differently after the code has been running for a bit of time, if you want to use time for benchmarking, you should at least "warm up" your code by running it several times, using the later time outputs as the ones that count. A better strategy is to use a benchmarking library such as Criterium, which will do the warmup for you, and much more.