Java System.nanoTime() – Examples
In this tutorial, we will learn about the Java System.nanoTime() function, and learn how to use this function to the current time in nanoseconds, with the help of examples.
nanoTime()
System.nanoTime() returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds.
The value returned by nanoTime() is the difference, measured in nanoseconds, between the current time and midnight, January 1, 1970 UTC.
Syntax
The syntax of nanoTime() function is
nanoTime()
Returns
The function returns long value.
Example 1 – nanoTime()
In this example, we will get the current time in the resolution of nanoseconds using System.nanoTime()
method.
Java Program
public class Example {
public static void main(String args[]) {
long nanoTime = System.nanoTime();
System.out.println("Current time in Nano Seconds : "+nanoTime);
}
}
Output
Current time in Nano Seconds : 126627153678685
Example 2 – nanoTime() – Difference
In this example, we will calculate the time taken by an empty for loop to iterate one thousand times, using System.nanoTime() method. We will capture the current time before and after the for loop. And the difference between the values returned by nanoTime() will give the execution time of this for loop in nanoseconds.
Java Program
public class Example {
public static void main(String args[]) {
long nanoTime1 = System.nanoTime();
for(int i=0; i < 1000; i++) {
}
long nanoTime2 = System.nanoTime();
long runTimeInNanoSeconds = nanoTime2 - nanoTime1;
System.out.println("Time taken by for loop : " + runTimeInNanoSeconds + " nano seconds");
}
}
Output
Time taken by for loop : 5106 nano seconds
Conclusion
In this Java Tutorial, we have learnt the syntax of Java System.nanoTime() function, and also learnt how to use this function with the help of examples.