如果我测量执行一段代码所花费的时间意味着我知道代码的效率如何? JAVA

时间:2012-02-18 23:37:54

标签: java profiling processing-efficiency performance

鉴于以下代码段,哪一个更有效?实际的方法returnSomething()也可以在现实中返回0,因此需要try / catch。

//piece one
long sleepTime = 200;
try{ sleepTime /= returnSomething();}
catch(Exception e){sleepTime = 200;}
private int returnSomething(){
   return 1;
}

              //or

//piece two
long sleepTime = 200;
if(returnSomething() == 3){sleepTime = 67;}
else if(returnSomething() == 2){sleepTime = 100;}
else if(returnSomething() == 1){sleepTime = 200;}
private int returnSomething(){
   return 1;
}

我试图弄清楚哪一段代码在处理器使用方面更有效,他们做同样的事情。我想知道我为测试编写的代码是否适合此目的,或者我是否可以对代码进行其他类型的测试。我的研究结果显示,第2部分的效率是9倍(执行时间缩短了9倍),即使它使用硬代码if语句并且始终执行最后一个if语句。

完整的工作计划

public class CodePerformanceTester
{
    public static void main(String[] args){
        CodePerformanceTester tester = new CodePerformanceTester();
        tester.start();
    }

    public void start(){
       double start = System.currentTimeMillis();
       long sleepTime = 200;
       for(int i=0; i<10000000; i++){

           //uncoment here the two lines below
           //try{ sleepTime /= returnSomething();}
           //catch(Exception e){sleepTime = 200;}

           //coment the IF STATEMENTS when above code uncomented
           if(returnSomething() == 3){sleepTime = 67;}
           else if(returnSomething() == 2){sleepTime = 100;}
           else if(returnSomething() == 1){sleepTime = 200;}
       }
       double end = System.currentTimeMillis();
       System.out.println("Execution time for 10 million iteration was "+(end-start)+" ms.");
    }


    private int returnSomething(){
       return 1;
    }
}

1 个答案:

答案 0 :(得分:1)

第一部分可能更慢,因为分割比比较价值更贵。