Home Java Java-get-example Java example to calculate the execution time

Related Tutorials


 
 

Share on Google+Share on Google+

Java example to calculate the execution time

Advertisement
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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2008

Related Tutorials

Discuss: Java example to calculate the execution time   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
venkatesh
November 22, 2011
Java

the execution times r changing for every run then how can i estimate the execution time of callMethod(),pls clarify
DMCA.com