lalakers4life
lalakers4life

Reputation: 59

Print execution time of function in seconds?

(time(get_report))

Gives me "Elapsed time 32038 ms". But I want seconds, not ms. How can I accomplish this in Clojure?

I want it to print like "Report took 32 seconds".

Update on how I have it now:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
   expr."
{:added "1.0"}
[expr]
`(let [start# (. System (nanoTime))
     ret# ~expr]
 (prn (str "Report print time: " (/ (double (- (. System (nanoTime))   start#)) 1000000000.0) " secs"))))

(time(get_report))

This is my gather_report function:

(defn gather_report []

(def list_of_isbns (split_isbns "src/clj_amazon/isbn_list.txt"))
(get_title_and_rank_for_all_isbns list_of_isbns)
)

Upvotes: 0

Views: 2592

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45736

This is the standard definition:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (. System (nanoTime))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
     ret#))

Note the division form? Just divide by 1000 to convert to seconds. You can change the message aswell:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (. System (nanoTime))
         ret# ~expr]
     (prn (str "Report print time: " (/ (double (- (. System (nanoTime)) start#)) 1000000000.0) " secs"))
     ret#))

The best way to find the source of something is to look up the Clojure docs for the function, and follow the" source" link.

And this is why you don't use def inside a function definition:

(defn test-fn [] 
    (def some-val 20)
    (* some-val some-val)

(test-fn)

(println some-val) 
; prints 20! 

def creates a global value. You certainly don't want that! Use let instead to limit the scope:

(defn test-fn [] 
    (let [some-val 20]
        (* some-val some-val)) 

Upvotes: 1

kongeor
kongeor

Reputation: 732

You can make a modified version of time macro tailored to your needs:

(defmacro sectime
  [expr]
  `(let [start# (. System (currentTimeMillis))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (currentTimeMillis)) start#)) 1000.0) " secs"))
     ret#))

Upvotes: 0

Related Questions