java.lang.System.nanoTime() returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. It returns the time since some fixed chosen time.

System.nanoTime() can be used to measure elapsed time between the execution of a piece of code in nano seconds.

Syntax:

public static long nanoTime();

Demo Program : Measuring Elapsed time in NanoSeconds Using System.nanoTime()

The below demo program illustrates how to measure elapsed time in the execution of a piece of a code in nano seconds.

package com.masterjavatutorial;

public class Example {

	public static void main(String[] args) {

		//Returns the current value of the running Java 
		// Virtual Machine's high-resolution time source, in nanoseconds.
		 long initialNanoTime = System.nanoTime(); 
		 for(int i=0; i < 10; i++){
		      System.out.println("count = "+i); 
		 }
         
		 long finalNanoTime = System.nanoTime();
		 
		 System.out.println("Time Take in NanoSeconds = "+(finalNanoTime - initialNanoTime));
		 
	}

}

Output of the above Program is as below:

count = 0
count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
Time Take in NanoSeconds = 1003332