VOOZH about

URL: https://www.geeksforgeeks.org/java/measure-time-taken-function-java/

⇱ How to measure time taken by a function in java ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to measure time taken by a function in java ?

Last Updated : 30 Apr, 2024

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:


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:


Output
Loop starts
Loop ends
Counting to 10000000 takes 18ms

Similar Articles

Comment
Article Tags:
Article Tags: