1

I am going through Groovy Closures, and I came to a particular section in Groovy in Action which talks about using Closures. I tweaked the code a little as below:-

def benchmark(int repeat, Closure worker){
    def start = System.nanoTime()
    repeat.times {worker(it)}
    def stop = System.nanoTime()
    return stop-start
}
def slow = benchmark(10){println('1')}
def fast = benchmark(10){println('1')}
println(slow)
println(fast)

Now the variable slow is always greater than fast. How is that possible? When we are calling the benchmark method with the same parameters each time?

PS:- Very new to SO community, do correct me if I made some mistake in asking question as above. Thanks

Saurav Kumar
  • 61
  • 1
  • 4

1 Answers1

0

It seems as though the first run tends to take longer than the second but in a longer series of runs there are often longer runtimes in the third or fourth run, and occasionally later in the series.

This code shows that the benchmark time reduces as the number of runs increases, indicating the long runtimes are primarily due to some 'startup' issues. The micro-benchmarking link above mentions this warmup effect.

def benchmark(int repeat, Closure worker){
    def start = System.nanoTime()
    repeat.times {worker(it)}
    def stop = System.nanoTime()
    return stop-start
}
[10,100,1000,10000,100000].each{
    def time=0
    for(int i=0; i<it; i++){
        buff=benchmark(100){}
      time+=buff
    }
   println("Average ${time/it} size ${it}")
 }
stegzzz
  • 407
  • 4
  • 9