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 次浏览

开启你的职业

完成课程,获得认证

开始
广告