Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Salman Yousaf

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring