如何用Java编写(并运行)正确的微基准测试?
我正在寻找一些代码示例和注释,以说明需要考虑的各种事情。
示例:基准测试应该测量时间/迭代还是迭代/时间,为什么?
相关:秒表基准测试是可接受的?
如何用Java编写(并运行)正确的微基准测试?
我正在寻找一些代码示例和注释,以说明需要考虑的各种事情。
示例:基准测试应该测量时间/迭代还是迭代/时间,为什么?
相关:秒表基准测试是可接受的?
当前回答
在Java中编写微基准测试有许多可能的陷阱。
首先:你必须计算各种随机占用时间的事件:垃圾收集、缓存效果(OS对文件的缓存效果和CPU对内存的缓存效果)、IO等。
第二:对于非常短的时间间隔,您不能相信测量时间的准确性。
第三:JVM在执行时优化代码。因此,在同一个jvm实例中不同的运行将变得越来越快。
My recommendations: Make your benchmark run some seconds, that is more reliable than a runtime over milliseconds. Warm up the JVM (means running the benchmark at least once without measuring, that the JVM can run optimizations). And run your benchmark multiple times (maybe 5 times) and take the median-value. Run every micro-benchmark in a new JVM-instance (call for every benchmark new Java) otherwise optimization effects of the JVM can influence later running tests. Don't execute things, that aren't executed in the warmup-phase (as this could trigger class-load and recompilation).
其他回答
我知道这个问题已经被标记为已回答,但我想提到两个帮助我们编写微基准的库
来自谷歌的卡尺
入门教程
http://codingjunkie.net/micro-benchmarking-with-caliper/ http://vertexlabs.co.uk/blog/caliper
来自OpenJDK的JMH
入门教程
避免JVM上的基准测试陷阱 使用JMH进行Java微基准测试 JMH简介
http://opt.sourceforge.net/ Java Micro Benchmark -确定不同平台上计算机系统的比较性能特征所需的控制任务。可用于指导优化决策和比较不同的Java实现。
jmh是最近添加到OpenJDK的,是由Oracle的一些性能工程师编写的。当然值得一看。
jmh是一个Java工具,用于构建、运行和分析用Java和其他针对JVM的语言编写的纳米/微/宏基准测试。
样本测试注释中隐藏着非常有趣的信息。
参见:
避免JVM上的基准测试陷阱 讨论jmh的主要优势。
还应该注意的是,在比较不同的实现时,分析微基准测试的结果可能也很重要。因此,应进行显著性检验。
这是因为在基准测试的大多数运行过程中,实现A可能比实现B更快,但A也可能有更高的差异,因此与B相比,A的测量性能收益将没有任何意义。
因此正确编写和运行微基准测试也很重要,但正确分析它也很重要。
在Java中编写微基准测试有许多可能的陷阱。
首先:你必须计算各种随机占用时间的事件:垃圾收集、缓存效果(OS对文件的缓存效果和CPU对内存的缓存效果)、IO等。
第二:对于非常短的时间间隔,您不能相信测量时间的准确性。
第三:JVM在执行时优化代码。因此,在同一个jvm实例中不同的运行将变得越来越快。
My recommendations: Make your benchmark run some seconds, that is more reliable than a runtime over milliseconds. Warm up the JVM (means running the benchmark at least once without measuring, that the JVM can run optimizations). And run your benchmark multiple times (maybe 5 times) and take the median-value. Run every micro-benchmark in a new JVM-instance (call for every benchmark new Java) otherwise optimization effects of the JVM can influence later running tests. Don't execute things, that aren't executed in the warmup-phase (as this could trigger class-load and recompilation).