The nanoTime()
function of the java.lang.System
class returns the precise value of time in nanoseconds (ns). The current value of running the Java Virtual Machine is returned. This value also provides nanosecond precision. The nanoTime()
function is related to measuring the elapsed time and is not relevant to the system or clock time.
The returned value shows nanoseconds until the fixed but arbitrary origin time. These values become meaningful if the differences are calculated between two values that are acquired within a similar instance of
static long nanoTime()
nanoTime()
does not take in any parameters.
This function returns the value of the current time in nanoseconds.
The following code will help us understand how the nanoTime()
method works. We can simply call this method to note the current time. Have a look at lines 6, 18, and the program output.
// Load librariesimport java.lang.*;public class nanotime {// Main methodpublic static void main(String[] args){long Time_start = System.nanoTime();System.out.println ("Initial program starting time: " + Time_start);// Display the table of 2.int i;int n=2, table;// This loop will generate multiples of 2// Uncomment to see 2x multiplesfor (i=1;i<=10;i++){table=n*i;//System.out.println (n+ "X" +i+ "="+table);}long nano_estimated_Time = System.nanoTime();System.out.println("Time taken to complete the execution of code in nanoseconds : "+nano_estimated_Time);System.out.println ("Time Difference: " + (nano_estimated_Time - Time_start));}}
// extract current jvm timepublic class EdPresso {public static void main(String[] args) {System.out.println("Time in nanoseconds = "+System.nanoTime());}}