![]() |
VOOZH | about |
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.
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:
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.
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:
Loop starts Loop ends Counting to 10000000 takes 18ms