Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Java example to calculate the execution time

Ads
 

Java example to calculate the execution time

This example program will describe you the way that how one can calculate or get the execution time of a method or program in java.

This example program will describe you the way that how one can calculate or get the execution time of a method or program in java.

Java example to calculate the execution time

     

get execution time

This example program will describe you the way that how one can calculate or get the execution time of a method or program in java. This can be done by subtracting the starting time of the program or method by the ending time of the method. In our example java program we are using System.currentTimeMillis() method for getting current time in milliseconds.

We have created a method callMethod() and before calling this method we have stored the current time in a variable startTime and after the method is done with its working we have stored the current time into another variable endTime. Now by subtracting the startTime with endTime we can calculate the execution time of method.

Here is the full example code of GetExecutionTime.java as follows:

GetExecutionTime.java

import java.util.*;
public class GetExecutionTimes
{
  public GetExecutionTimes(){}
  public static void main(String args[])
  {
  long startTime = System.currentTimeMillis();
  GetExecutionTimes ext=new GetExecutionTimes();
  ext.callMethod();
  long endTime = System.currentTimeMillis();
  System.out.println("Total elapsed time in execution of 
   method callMethod() is :"
(endTime-startTime));
  }
  public void callMethod(){
  System.out.println("Calling method");
  for(int i=1;i<=10;i++)
  {
  System.out.println("Value of counter is "+i);
  }
  }
}

 Output:

C:\javaexamples>javac GetExecutionTimes.java

C:\javaexamples>java GetExecutionTimes
Calling method
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4
Value of counter is 5
Value of counter is 6
Value of counter is 7
Value of counter is 8
Value of counter is 9
Value of counter is 10
Total elapsed time in execution of method callMethod() is :16

Download Source Code

Ads

Ads