计算 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");
      // converting it into seconds
      float sec= msec/1000F;
      System.out.println(sec + " seconds");
      // converting it into minutes
      float minutes=sec/60F;
      System.out.println(minutes + " minutes");
   }
}

输出

300.0 milliseconds
0.3 seconds
0.0050000004 minutes

更新于:26-6 月-2020

186 次查看

开启你的 职业生涯

完成课程,获得认证

开始学习
广告