Java System nanoTime() 方法



描述

Java System nanoTime() 方法返回系統最精確計時器的當前值(以納秒為單位)。返回的值表示自某個固定但任意的時刻(未來某個時刻,因此值可能為負數)以來的納秒數,並提供納秒精度,但不一定具有納秒準確性。

宣告

以下是java.lang.System.nanoTime() 方法的宣告

public static long nanoTime()

引數

返回值

此方法返回系統計時器的當前值(以納秒為單位)。

異常

示例:獲取當前時間(納秒)

以下示例演示了 Java System nanoTime() 方法的使用。在此示例中,我們使用 System.nanoTime() 方法列印當前時間(納秒)。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current Time in nanoseconds = 105909690470100

示例:使用當前時間(納秒)檢查程式碼的執行時間

以下示例演示了 Java System currentTimeMillis() 方法的使用。在此示例中,我們透過獲取以毫秒為單位的當前時間來記錄程式碼片段的開始時間,然後在 for 迴圈語句中執行程式碼。迴圈完成後,我們再次透過獲取以毫秒為單位的當前時間來記錄結束時間。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Program took 800 nanoseconds
java_lang_system.htm
廣告
© . All rights reserved.