We can measure the time taken by a function in Java with the help of java.lang.System.nanoTime() and java.lang.System.currentTimeMills() methods. These methods return the current time in nanoseconds and milliseconds. We can call this method at the beginning and at the end of the function and by the difference we measure the time taken by the function.
1. Using System.nanoTime()
The most common approach to calculating execution time is by utilizing the System.nanoTime() method, that provides a high-resolution timer. Here’s how you can use it:
Java
// Java Program to demonstrate use// of System.nanoTime() methodimport java.io.*;// Driver classpublic class ExecutionTimeExample {    // main function    public static void main(String[] args)    {        // Start measuring execution time        long startTime = System.nanoTime();        count_function(10000000);        // Stop measuring execution time        long endTime = System.nanoTime();        // Calculate the execution time in milliseconds        long executionTime            = (endTime - startTime) / 1000000;        System.out.println("Counting to 10000000 takes "                           + executionTime + "ms");    }       // A dummy function that runs a loop x times    public static void count_function(long x)    {        System.out.println("Loop starts");        for (long i = 0; i < x; i++)            ;        System.out.println("Loop ends");    }} | 
Loop starts Loop ends Counting to 10000000 takes 12ms
The System.nanoTime() method returns the current system time in nanoseconds. By capturing the start and end times and calculating the difference, we obtain the execution time in nanoseconds. To convert it to milliseconds, divide the difference by 1,000,000.
2. Using System.currentTimeMillis()
An alternative approach to measure execution time is by using System.currentTimeMillis(). While this method provides lower precision than System.nanoTime(), it is still suitable for most use cases. Here’s an example:
Java
// Java Program to demonstrate use// of System.currentTimeMillis() methodimport java.io.*;// Driver Classpublic class Time {    // main function    public static void main(String[] args)    {        // starting time        long start = System.currentTimeMillis();             // start of function        count_function(10000000);        // end of function        // ending time        long end = System.currentTimeMillis();        System.out.println("Counting to 10000000 takes " +                                    (end - start) + "ms");    }    // A dummy function that runs a loop x times    public static void count_function(long x)    {        System.out.println("Loop starts");        for (long i = 0; i < x; i++)            ;        System.out.println("Loop ends");    }} | 
Loop starts Loop ends Counting to 10000000 takes 18ms
