Program Java do obliczania czasu wykonywania metod

W tym przykładzie nauczymy się obliczać czas wykonywania normalnych metod i metod rekurencyjnych w Javie.

Aby zrozumieć ten przykład, należy znać następujące tematy dotyczące programowania w języku Java:

  • Metody Java
  • Rekursja Java

Przykład 1: Program w języku Java do obliczania czasu wykonania metody

 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"); ) )

Wynik

 Czas wykonania metody obliczeniowej: Czas wykonania: 656100 nanosekund

W powyższym przykładzie utworzyliśmy metodę o nazwie display(). Metoda wyświetla instrukcję w konsoli. Program oblicza czas wykonania metody display().

Tutaj użyliśmy metody nanoTime()w Systemklasie. nanoTime()Metoda zwraca aktualną wartość bieżącą JVM w nanosekund.

Przykład 2: Oblicz czas wykonania metody rekurencyjnej

 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 object of Main class Main obj = new Main(); // get the start time long start = System.nanoTime(); // call the method obj.factorial(128); // get the end time long end = System.nanoTime(); // execution time in seconds long execution = (end - start); System.out.println("Execution time of Recursive Method is"); System.out.println(execution + " nanoseconds"); ) )

Wynik

 Czas wykonania metody rekurencyjnej to 18600 nanosekund

W powyższym przykładzie obliczamy czas wykonania metody rekurencyjnej o nazwie factorial().

Interesujące artykuły...