goo*_*ing 8 java performance time nanotime
class testx
{
public testx()
{
long startTime = System.nanoTime();
System.out.println((System.nanoTime() - startTime));
}
public static void main(String args[])
{
new testx();
new testx();
new testx();
}
}
Run Code Online (Sandbox Code Playgroud)
我总是得到类似的结果7806 660 517.为什么第一次通话比其他通话时间多10倍?
Lou*_*man 22
因为JVM在那时第一次加载了一堆类.一旦第一System.nanoTime()的回报,你已经加载System.class和testx.class,但一旦System.out.println进入图片,我怀疑很多I/O类的获取加载起来,这需要一些时间.
无论如何,这不是一个很好的基准测试技术; 在开始测量之前,你应该通过运行~10000次迭代来加热JIT.或者(并且最好)使用像Caliper这样的预制基准测试工具.