How to Calculate Execution time of a Program in Java

Hey Coders!
So in this tutorial, we will learn how we can Calculate the execution time of a program in Java.

Java is an object-oriented language (i.e) everything is in objects and classes, therefore, we have two ways of taking inputs from the user. They are:

  1.  Using Scanner object
  2. Using an object of BufferedReader class

BufferedReader is a bit faster when compared to scanner as scanner does parsing of input data while BufferedReader simply reads the sequence of characters. Hence for faster execution of programs with multiple threads, we use the BufferedReader class.

Code to calculate the execution time of a Program

import java.io.*;
import java.lang.*;
class ExecutionTime
{
    public static void main(String args[])throws IOException
    {
        long start = System.nanoTime(); 
        int num1, num2, mul;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter first number: ");
        num1 = Integer.parseInt(br.readLine());

        System.out.print("Enter second number: ");
        num2 = Integer.parseInt(br.readLine());
        
        mul = num1 * num2;
        System.out.println("Multiplication of two numbers is: "+mul);

        long end = System.nanoTime();
        long exec = end - start;
        double inSeconds = (double)exec / 1_000_000_000.0;

        System.out.println("The program takes "+exec+" nanoseconds that is "+inSeconds+" seconds to execute.");        
    }
}

Output:

Enter first number: 4
Enter second number: 5
Multiplication of two numbers is: 20
The program takes 2560502743 nanoseconds that is 2.560502743 seconds to execute.

Explanation

  1. Firstly we initialise a variable with System.nanoTime()  a method, which returns the current value of the system time, in nanoseconds.
  2. Next, we write the code we want to execute.
  3. In the end, we initialise another variable with System.nanoTime() and subtract both the time variables to get the execution time.
  4. The execution time obtained is in Nanoseconds. We can divide the nanoseconds by 1,000,000,000 to obtain the execution time in seconds.

Hope you’ve understood the code 🙂
Any questions please feel free to drop in your comments.

You can also read:

Leave a Reply

Your email address will not be published. Required fields are marked *