Java 程式中以毫秒為單位計算運算的經過時間


若要計算 Java 程式中運算的經過時間(以毫秒為單位),需使用 System.currentTimeMillis() 方法。java.lang.System.currentTimeMillis() 返回當前時間(以毫秒為單位)。

宣告 −java.lang.System.currentTimeMillis() 的宣告如下 −

public static long currentTimeMillis()

此方法返回當前時間與 1970 年 1 月 1 日午夜(UTC 或紀元時間)之間的毫秒數時間差。

我們來看一個 Java 程式,該程式計算運算的經過時間(以毫秒為單位) −

示例

演示

public class Example {
   public static void main(String[] args) throws Exception {
      // finding the time before the operation is executed
      long start = System.currentTimeMillis();
      for (int i = 0; i <5; i++) {
         Thread.sleep(60);
      }
      // finding the time after the operation is executed
      long end = System.currentTimeMillis();
      // finding the time difference
      float msec = end - start;
      System.out.println(msec + " milliseconds");
   }
}

輸出

301.0 milliseconds

更新日期:25-Jun-2020

519 次瀏覽

開啟你的職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.