Monday 18 March 2013

How To Calculate Execution Time Of Java Program

Leave a Comment

Using new Date.getTime();

package Core;

import java.util.Date;


public class ExecutionTime {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   ExecutionTime obj = new ExecutionTime();
   
   long startTime = new Date().getTime();
   obj.method();
   long endTime = new Date().getTime();
   System.out.println("Time Taken: "+ (endTime - startTime));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}



Using System.currentTimeMillis()

package Core;

import java.util.Date;

public class ExecutionTimeSystem {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   ExecutionTime obj = new ExecutionTime();
   
   long startTime = System.currentTimeMillis();
   obj.method();
   long endTime = System.currentTimeMillis();
   System.out.println("Time Taken: "+ (endTime - startTime));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


0 comments:

Post a Comment