English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program to calculate the execution time of a method

Java Examples Comprehensive

In this example, we will learn to calculate the execution time of regular and recursive methods in Java.

To understand this example, you should understand the followingJava ProgrammingTopic:

Example1:Java program to calculate the execution time of a method

class Main {
  //Create a method
  public void display() {
    System.out.println("Calculate the execution time of the method:");
  }
  // Main Method
  public static void main(String[] args) {
    //Create an object of Main class
    Main obj = new Main();
    //Get the start time
    long start = System.nanoTime();
    // Call Method
    obj.display();
    //Get the end time
    long end = System.nanoTime();
    //Execution time
    long execution = end - start;
    System.out.println("Execution time: ") + execution + " Nanoseconds ");
  }
}

Output Result

Calculate the execution time of the method:
Execution time: 656100 nanoseconds

In the above example, we created a method named display(). This method outputs a statement to the specified console. The program calculates the execution time of the display() method.

Here, we use the nanoTime() method of the System class. The nanoTime() method returns the current value of the running JVM in nanoseconds.

Example2:Calculate the execution time of the recursive method

class Main {
  //Create a recursive method
  public int factorial(int n) {
    if (n != 0)  //Termination Condition
        return n * factorial(n-1); //Recursive Call
    else
        return 1;
}
  // Main Method
  public static void main(String[] args) {
    //Create an object of Main class
    Main obj = new Main();
    //Get the start time
    long start = System.nanoTime();
    //Call Method
    obj.factorial(128);
    //Get the end time
    long end = System.nanoTime();
    //Execution Time (Seconds)
    long execution = (end - );
    System.out.println("The execution time of the recursive method is");
    System.out.println(execution + " Nanoseconds ");
  }
}

Output Result

The execution time of the recursive method is
18600 Nanoseconds

In the above example, we are calculating the execution time of the recursive method named factorial().

Java Examples Comprehensive