What is the System.nanoTime() function in Java?

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 JVMJava Virtual Machine. For instance, we can check how much time a code takes to complete execution.

Syntax

static long nanoTime()

Parameters

nanoTime() does not take in any parameters.

Return value

This function returns the value of the current time in nanoseconds.

Code

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 libraries
import java.lang.*;
public class nanotime {
// Main method
public 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 multiples
for (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 time
public class EdPresso {
public static void main(String[] args) {
System.out.println("Time in nanoseconds = "+System.nanoTime());
}
}

Free Resources