Welcome! Please see the About page for a little more info on how this works.

0 votes
in Compiler by

Am trying to get the execution time of a function in clojure,so i decided to store the system nano time in variable called start and then after the method executes i get it and get the difference and print it out..Here is the code
(def start(System/nanoTime)) ;;there is some functional call here (def end(System/nanoTime)) ;;below i need code to print the difference of the two (println "The call took these nano seconds to execute")

1 Answer

+2 votes
by
selected by
 
Best answer

def defines a global var in the current namespace. And defining global vars to time a function call is probably not a good idea. For example, let's say you want to measure the call (+ 1 2). You can use let to do the timing (as opposed to def), and use println to print the time taken, as follows:

(let [start (System/nanoTime)
      ret (+ 1 2)
      end (System/nanoTime)]
   (println (str "Elapsed time: " (- end start) " ns"))
   ret)

clojure.core/time captures this exact thing into a macro (with one difference, it prints the time taken in milliseconds). So, the above code would be equivalent to (time (+ 1 2)). Check out (source time) to see how that's done.

by
Can you modify your code to output time in seconds?
by
Sure I can. You'd have you divide the number by `1000000000.0` to convert to seconds.

Here's a modified version of `clojure.core/time` that prints the time in seconds.

    (defmacro time-sec [expr]
      `(let [start# (. System (nanoTime))
             ret# ~expr]
         (prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000000.0) " s"))
         ret#))

And to use it, you'd do `(time-sec (+ 1 2))`.
...