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.