Java System nanoTime() Method



Description

The Java System nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.

Declaration

Following is the declaration for java.lang.System.nanoTime() method

public static long nanoTime()

Parameters

NA

Return Value

This method returns the current value of the system timer, in nanoseconds.

Exception

NA

Example: Getting Current Time in Nanoseconds

The following example shows the usage of Java System nanoTime() method. In this example, we're printing the current time in nanoseconds using System.nanoTime() method.

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      // returns the current time in nanoseconds
      System.out.print("Current Time in nanoseconds = ");
      System.out.println(System.nanoTime());
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Current Time in nanoseconds = 105909690470100

Example: Using Current Time in nano seconds to Check Execution Time of a Code

The following example shows the usage of Java System currentTimeMillis() method. In this example, we've noted down the start time of a code snippet by getting the current time in millis and then code is executed in a for loop statement. Once loop is completed, we've again noted down the end time by getting the current time in milliseconds.

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args){

      // start time of the code snippet
      long startTime = System.nanoTime();

      int sum = 0;
      // a time consuming task
      for (int i = 0; i < 10; i++) {
         sum += i;
      }
      // end time of the code snippet
      long endTime = System.nanoTime();

      System.out.println("Program took " +
         (endTime - startTime) + "nanoseconds") ;
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Program took 800 nanoseconds
java_lang_system.htm