我正在浏览Groovy Closures,我来到Groovy in Action的一个特定部分,讨论如何使用Closures。我稍微调整了一下代码: -
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)
现在变量slow总是大于fast。怎么可能?当我们每次使用相同的参数调用基准测试方法时?
PS: - 对SO社区来说很新,如果我在上面提问时犯了一些错误,请纠正我。 感谢
答案 0 :(得分:0)
似乎第一次运行往往需要比第二次运行更长的时间,但是在更长的一系列运行中,第三次或第四次运行通常会有更长的运行时间,有时甚至会在系列的后期运行。
此代码显示基准时间随着运行次数的增加而减少,表明长运行时间主要是由于某些“启动”问题。上面的微观基准链接提到了这种预热效果。
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}")
}