When we write an algorithm in any language, we must check the execution time of that algorithm. A bad code might eat a ginormous amount of resources that will result in slow execution of the program. There might be several ways to find the running time of an algorithm, but the simplest way is to get the start time (at the start of the program) and end time (at the end of the program) and then calculate the difference between the end time and start time.
In the Java program, use currentTimeMillis() at the start and end of the code to get the start and end time in milliseconds. Here is the sample Java code to find the Fibonacci series, and I have used currentTimeMillis() to calculate the program’s running time.
public class FibonacciCalculator{
public long fibonacci(long num){
if((num == 0) || (num == 1)){
return num;
}else{
return fibonacci(num-1) + fibonacci(num-2);
}
}
public void displayFibonacci(){
for(int i=0; i<=45; i++){
System.out.println("Fibo " + i + "= " + fibonacci(i));
}
}
}
import java.util.concurrent.TimeUnit;
public class FibonacciTest{
public static void main(String[] args){
long startMS = System.currentTimeMillis();
long startS = TimeUnit.MILLISECONDS.toSeconds(startMS); // convert to seconds
FibonacciCalculator fib = new FibonacciCalculator();
fib.displayFibonacci();
long endMS = System.currentTimeMillis();
long endS = TimeUnit.MILLISECONDS.toSeconds(endMS);
long diff = endS - startS;
System.out.println("Total Execution time: " + diff + "seconds");
}
}
The output of the code is as follows…
Fibo 0= 0
Fibo 1= 1
Fibo 2= 1
Fibo 3= 2
Fibo 4= 3
Fibo 5= 5
Fibo 6= 8
Fibo 7= 13
Fibo 8= 21
Fibo 9= 34
Fibo 10= 55
Fibo 11= 89
Fibo 12= 144
Fibo 13= 233
Fibo 14= 377
Fibo 15= 610
Fibo 16= 987
Fibo 17= 1597
Fibo 18= 2584
Fibo 19= 4181
Fibo 20= 6765
Fibo 21= 10946
Fibo 22= 17711
Fibo 23= 28657
Fibo 24= 46368
Fibo 25= 75025
Fibo 26= 121393
Fibo 27= 196418
Fibo 28= 317811
Fibo 29= 514229
Fibo 30= 832040
Fibo 31= 1346269
Fibo 32= 2178309
Fibo 33= 3524578
Fibo 34= 5702887
Fibo 35= 9227465
Fibo 36= 14930352
Fibo 37= 24157817
Fibo 38= 39088169
Fibo 39= 63245986
Fibo 40= 102334155
Fibo 41= 165580141
Fibo 42= 267914296
Fibo 43= 433494437
Fibo 44= 701408733
Fibo 45= 1134903170
Total Execution time: 15seconds