How to Find Method Execution Time in Java

Performance is an important technical feature to focus on when you write Java programs. One of the easiest ways to measure performance is to check the time taken by each method. Java provides a utility class System which is capable of returning the number of milliseconds elapsed since 1st January 1970. Using this we can measure the value before the method call and after the method call. The difference will give us the time taken by the method.

Following Java program shows how we can measure method execution time,

 * Java program to measure method execution time
public class MethodExecutionTime {
    public static void main(String[] args) {
        MethodExecutionTime me = new MethodExecutionTime();
        long startTime = System.currentTimeMillis();
        float v = me.callSlowMethod();
        long endTime = System.currentTimeMillis();
        System.out.println("Seconds take for execution is:"+(endTime-startTime)/1000);
    /* Simulates a time consuming method */
    private float callSlowMethod() {
        float j=0;
        for(long i=0;i<5000000000L;i++) {
            j = i*i;
        return j;