用 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 and converting it into seconds
      float sec = (end - start) / 1000F; System.out.println(sec + " seconds");
   }
}

輸出

0.3 seconds

更新於:2020-06-26

12K+ 瀏覽

開啟你的 事業

完成該課程,獲得認證

開始
廣告