Java System currentTimeMillis() 方法



描述

Java System currentTimeMillis() 方法返回以毫秒為單位的當前時間。返回值的時間單位是毫秒,值的粒度取決於底層作業系統,可能更大。

例如,許多作業系統以數十毫秒為單位測量時間。

宣告

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

public static long currentTimeMillis()

引數

返回值

此方法返回當前時間與 1970 年 1 月 1 日午夜 UTC(協調世界時)之間的差值(以毫秒為單位)。

異常

示例:獲取以毫秒為單位的當前時間

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

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

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

輸出

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

Current Time in milliseconds = 1719557974290

示例:使用以毫秒為單位的當前時間來檢查程式碼的執行時間

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

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) throws InterruptedException {

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

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

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

輸出

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

Program took 1097 ms
java_lang_system.htm
廣告
© . All rights reserved.