0

I tried to find execution time of two methods in java. both the method doing same functionality but different logic, the execution time differs in lot. then i tried to find the execution time of same method two time, but the execution time are not even almost equal differs by multiples of 10's. so please advise me, how measure the exact execution time of java method. `

public static void main(String[] args) throws Throwable {

    double t11 = System.nanoTime();
    System.out.println(test(2, 32));
    double t12 = System.nanoTime();
    System.out.println("Total time taken : "+(t12-t11));

    double t1 = System.nanoTime();
    System.out.println(test(2, 32));
    double t2 = System.nanoTime();
    System.out.println("Total time taken : "+(t2-t1));

}

public static long test(int num1, int num2){
    long value = num1;
    for(int i=2; i<=num2; i++) {
        value *= num1;
    }
    return value;
}

Output : 4294967296 Total time taken : 207084.0 4294967296 Total time taken : 35621.0

  • @Andreas, its possible a duplicate. – Chethan kumar B N Nov 21 '16 at 05:57
  • My question is 'why the execution time of same method is differed by almost 5.81 times', for reference see the output of the execution time for same method. – Chethan kumar B N Nov 21 '16 at 06:00
  • No, your Question explicitly asked how to measure precisely execution time of a method call. That is a duplicate of many Questions including the linked Question. If you read some of those duplicates you would learn that such micro benchmarking is tricky. The JVM warms up when launching with various background tasks so initial performance may suffer. And just-in-time compiling may cause later repeat executions to run faster. And the HotSpot runtime optimizing may cause repeated code to run faster. – Basil Bourque Nov 21 '16 at 06:19
  • @BasilBourque, thanks for your comments. – Chethan kumar B N Nov 21 '16 at 06:31

0 Answers0