Write a Java Program to Calculate the Execution Time of Methods

Write a Java Program to Calculate the Execution Time of Methods

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Main {

  // create a method
  public void display() {
    System.out.println("Calculating Method execution time:");
  }

  // main method
  public static void main(String[] args) {

    // create an object of the Main class
    Main obj = new Main();

    // get the start time
    long start = System.nanoTime();

    // call the method
    obj.display();

    // get the end time
    long end = System.nanoTime();

    // execution time
    long execution = end - start;
    System.out.println("Execution time: " + execution + " nanoseconds");
  }
}

Final Output

Leave a Comment