为什么两次连续调用同一方法会产生不同的执行时间? [英] Why do two consecutive calls to the same method yield different times for execution?

查看:200
本文介绍了为什么两次连续调用同一方法会产生不同的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例代码:

public class TestIO{
public static void main(String[] str){
    TestIO t = new TestIO();
    t.fOne();
    t.fTwo();
    t.fOne();
    t.fTwo();
}


public void fOne(){
    long t1, t2;
    t1 = System.nanoTime();
    int i = 10;
    int j = 10;
    int k = j*i;
    System.out.println(k);
    t2 = System.nanoTime();
    System.out.println("Time taken by 'fOne' ... " + (t2-t1));
}

public void fTwo(){
    long t1, t2;
    t1 = System.nanoTime();
    int i = 10;
    int j = 10;
    int k = j*i;
    System.out.println(k);
    t2 = System.nanoTime();
    System.out.println("Time taken by 'fTwo' ... " + (t2-t1));
}

}

这将提供以下输出: 100 'fOne'花费的时间... 390273 100 'fTwo'花费的时间... 118451 100 'fOne'花费的时间... 53359 100 'fTwo'花费的时间... 115936 按任意键继续 . .

This gives the following output: 100 Time taken by 'fOne' ... 390273 100 Time taken by 'fTwo' ... 118451 100 Time taken by 'fOne' ... 53359 100 Time taken by 'fTwo' ... 115936 Press any key to continue . . .

为什么第一次执行相同方法要比连续调用花费更多时间(明显更多)?

Why does it take more time (significantly more) to execute the same method for the first time than the consecutive calls?

我尝试将-XX:CompileThreshold=1000000赋予命令行,但是没有区别.

I tried giving -XX:CompileThreshold=1000000 to the command line, but there was no difference.

推荐答案

有几个原因. JIT(及时)编译器可能尚未运行. JVM可以进行不同调用之间的优化.您正在测量经过的时间,因此您的计算机上可能正在运行Java以外的东西.处理器和RAM缓存在后续调用中可能是热"的.

There are several reasons. The JIT (Just In Time) compiler may not have run. The JVM can do optimizations that differ between invocations. You're measuring elapsed time, so maybe something other than Java is running on your machine. The processor and RAM caches are probably "warm" on subsequent invocations.

您确实需要进行多次调用(成千上万次)才能获得准确的每种方法执行时间.

You really need to make multiple invocations (in the thousands) to get an accurate per method execution time.

这篇关于为什么两次连续调用同一方法会产生不同的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆