# Clojure code summary analysis

Hi Clojure Experts,

I am trying to do some timing tests in Clojure 1.3 and I thought I was asking a question based on an existing piece of code that solves a differential equation adapted from this blog post .

The code follows:

``````;; the differential equation is
;; dy/dt = f(y,t) = t - y

(defn f [t y] (- t y))

;; solve using Euler method
(defn solveEuler [t0 y0 h iter]
(if (> iter 0)
(let [t1 (+ t0 h)
y1 (+ y0 (* h (f t0 y0)))]
(recur t1 y1 h (dec iter)))
[t0 y0 h iter]))

(defn multipleSolveEuler []
(let [steps '(1 10 100 1000 10000 100000)
results (map #(second (solveEuler 0.0 0.0 (/ 1.0 %) %)) steps)
errors  (map #(- (Math/exp -1) %) results)]
(partition 3 (interleave steps results errors))))

(def *cpuspeed* 2.0)

(defmacro cyclesperit [expr its]
`(let [start# (. System (nanoTime))
ret# ( ~@expr (/ 1.0 ~its) ~its )
finish# (. System (nanoTime))]
(int (/ (* *cpuspeed* (- finish# start#)) ~its))))

(defn solveEuler-2 [t0 y0 h its]
(let [zero (int 0)]
(loop [t0 (double t0), y0 (double y0), h (double h), its (int its)]
(if (> its zero)
(let [t1 (+ t0 h)
y1 (+ y0 (* h (- t0 y0)))]
(recur t1 y1 h (dec its)))
[t0 y0 h its]))))
```

```

So when I say

``````(time solveItEuler-2 0.0 1.0 (/ 1.0 1000000000) 1000000000))
```

```

I get 6004.184ms time on a 6 month Macbook pro. I issue the command again and I communicate at the same time. But when I run it 3 times, I get the time in the 3500ms range. I've noticed this before for other code snippets and wondered why this is the case. I guess I am expecting roughly the same execution time for sequential runs.

Don't I understand how "time" works, am I missing something or is there some caching going on under the hood?

Thank.

+3

source to share

It is not `time`

that relevant, but rather a JVM optimizing code at runtime. What you observe is typical; the execution time drops and then stabilizes after about 3 calls.

+7

source

I recommend using the Criterium library for benchmarking. It is designed to combat the pitfalls of benchmarking code that runs on the JVM.

+7

source

(This is a response to Viebel's request for more information, which became too many characters for a single comment. This is not an answer to the question.

There are quite a few degrees of freedom: JVM GC and heap settings, startup time, number of warm-up runs, data structures used, size of inline methods.

+2

source