How to measure time taken by a function in java ?
Last Updated :
06 Sep, 2023
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
import java.io.*;
public class ExecutionTimeExample {
public static void main(String[] args)
{
long startTime = System.nanoTime();
count_function( 10000000 );
long endTime = System.nanoTime();
long executionTime
= (endTime - startTime) / 1000000 ;
System.out.println( "Counting to 10000000 takes "
+ executionTime + "ms" );
}
public static void count_function( long x)
{
System.out.println( "Loop starts" );
for ( long i = 0 ; i < x; i++)
;
System.out.println( "Loop ends" );
}
}
|
Output
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
import java.io.*;
public class Time {
public static void main(String[] args)
{
long start = System.currentTimeMillis();
count_function( 10000000 );
long end = System.currentTimeMillis();
System.out.println( "Counting to 10000000 takes " +
(end - start) + "ms" );
}
public static void count_function( long x)
{
System.out.println( "Loop starts" );
for ( long i = 0 ; i < x; i++)
;
System.out.println( "Loop ends" );
}
}
|
Output
Loop starts
Loop ends
Counting to 10000000 takes 18ms
Similar Articles
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...