参见英文答案 >
How do I write a correct micro-benchmark in Java? 11个
我有一个用Scala编写的程序.我想测量不同独立代码块的执行时间.当我以明显的方式(即在每个块之前和之后插入System.nanoTime())时,我观察到执行时间取决于块的顺序.前几个块总是花费比其他块更多的时间.
我有一个用Scala编写的程序.我想测量不同独立代码块的执行时间.当我以明显的方式(即在每个块之前和之后插入System.nanoTime())时,我观察到执行时间取决于块的顺序.前几个块总是花费比其他块更多的时间.
我创建了一个简单的例子来重现这种行为.为简单起见,所有代码块都是相同的,并为整数数组调用hashCode().
package experiments import scala.util.Random /** * Measuring execution time of a code block * * Minimalistic example */ object CodeBlockMeasurement { def main(args: Array[String]): Unit = { val numRecords = args(0).toInt // number of independent measurements val iterations = args(1).toInt // Changes results a little bit,but not too much // val records2 = Array.fill[Int](1)(0) // records2.foreach(x => {}) for (_ <- 1 to iterations) { measure(numRecords) } } def measure(numRecords: Int): Unit = { // using a new array every time val records = Array.fill[Int](numRecords)(new Random().nextInt()) // block of code to be measured def doSomething(): Unit = { records.foreach(k => k.hashCode()) } // measure execution time of the code-block elapsedtime(doSomething(),"HashCodeExperiment") } def elapsedtime(block: => Unit,name: String): Unit = { val t0 = System.nanoTime() val result = block val t1 = System.nanoTime() // print out elapsed time in milliseconds println(s"$name took ${(t1 - t0).todouble / 1000000} ms") } }
运行numRecords = 100000和iterations = 10的程序后,我的控制台如下所示:
HashCodeExperiment took 14.630283 ms
HashCodeExperiment took 7.125693 ms
HashCodeExperiment took 0.368151 ms
HashCodeExperiment took 0.431628 ms
HashCodeExperiment took 0.086455 ms
HashCodeExperiment took 0.056458 ms
HashCodeExperiment took 0.055138 ms
HashCodeExperiment took 0.062997 ms
HashCodeExperiment took 0.063736 ms
HashCodeExperiment took 0.056682 ms
有人可以解释为什么会这样吗?不应该都一样吗?哪个是真正的执行时间?
非常感谢,
彼得
Environment parameters:
OS: ubuntu 14.04 LTS (64 bit)
IDE: IntelliJ IDEA 2016.1.1 (IU-145.597)
Scala: 2.11.7