JAVA中如何获取毫秒和微秒数

Python018

JAVA中如何获取毫秒和微秒数,第1张

一、获取毫秒数的代码

(1)System.currentTimeMillis() 这种方式速度最快。

(2)Calendar.getInstance().getTimeInMillis() 这种方式速度最慢。

二、获取微秒数的代码:

微秒使用System.nanoTime()方法:如果Java程序需要高精度的计时,如1毫秒或者更小,使用System.nanoTime()方法,可以满足需求。

扩展资料:

获取微秒函数System.nanoTime() 的隐患:

System.currentTimeMillis() 起始时间是基于 1970.1.1 0:00:00 这个确定的时间的,而System.nanoTime()是基于cpu核心的时钟周期来计时,它的开始时间是不确定的。

但是在多核处理器上,由于每个核心的开始时间不确定,那么

“long start = System.nanoTime()String ip = Utilities.getIpByUrl(url)long cost = System.nanoTime() - start  ”

这段代码有可能会运行在两个不同的cpu核心上,从而导致得到的结果完全不符逻辑。

使用Date类的getTime()方法

下面是示例代码,比如你要统计代码的执行时间:

import java.util.Date

public class Test {

    public static void main(String[] args) {

        long begin = new Date().getTime()

        double d = 4

        for (int i = 0 i < 200000 i++){

            d += 4

        }

        System.out.println(d)

        long end = new Date().getTime()

        System.out.println(end - begin)

    

    }

}

下面再看一下getTime的定义:

    /**

     * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

     * represented by this <tt>Date</tt> object.

     *

     * @return  the number of milliseconds since January 1, 1970, 00:00:00 GMT

     *          represented by this date.

     */

    public long getTime() {

        return getTimeImpl()

    }

milliseconds就是微妙的意思,所以getTime的精度是微妙