zoukankan      html  css  js  c++  java
  • currentTimeMillis与 nanoTime

    时间单位换算

    1s=10^3ms(毫秒)=10^6μs(微秒)=10^9ns(纳秒)=10^12ps(皮秒)=10^15fs(飞秒)=10^18as(阿秒)=10^21zm(仄秒)=10^24ym(幺秒) 


    currentTimeMillisnanoTimejava.lang.System中提供的提供的两个方法。


    1、public static long currentTimeMillis();

    返回当前时间与1970.1.1 UTC 零点之间的时间差,以毫秒为单位。

    调用:System.currentTimeMillis(); 

    注意:当返回值的时间单位是毫秒时,值的粒度取决于底层操作系统,并且粒度可能更大。例如,许多操作系统以几十毫秒为单位测量时间。

    好处:可与Date很方便的进行转换。

    public class MainClass {
        public static void main(String[] args) {
            long l1 = System.currentTimeMillis();
            System.out.println(l1);// 1480490262340
            Date d = new Date(l1);
            System.out.println(d);// Wed Nov 30 15:17:42 CST 2016
            long l2 = d.getTime();
            System.out.println(l2);// 1480490262340
        }
    }

    缺点:在CPU速度越来越快的今天,1毫秒已经成了一个相对较长的时间段,用它来测量代码执行的时间时,结果可能不是很理想。

    Date的源代码中有构造器:

        public Date() {
            this(System.currentTimeMillis());
        }

    可知new Date()其实就是在调用System.currentTimeMillis(),且Date类中getTime()方法间接返回的就是System.currentTimeMillis()的值。

    2、public static long  nanoTime();

    在JDK5中增加的方法,返回系统计时器的当前值,以纳秒为单位;精确度是currentTimeMillis()的10^6倍

    调用:System.nanoTime(); 

    注意:此方法只能用于测量已过的时间,与系统或钟表时间的其他任何时间概念无关。nanoTime不能用来计算当前时间。

    计算代码执行时间代码:

    long s = System.nanoTime(); 
    .... 
    System.out.println(System.nanoTime() - s);

     

  • 相关阅读:
    设计模式(五)——单例模式
    设计模式(四)——工厂模式
    设计模式(三)—— 装饰者模式
    设计模式(二)—— 观察者模式
    JAVA环境配置
    在线求中位数
    不能对自己期望太大,但总是要拼一拼
    Leetcode | String to Integer (atoi)
    Leetcode | Simplify Path
    Leetcode | Longest Common Prefix
  • 原文地址:https://www.cnblogs.com/SQP51312/p/6117766.html
Copyright © 2011-2022 走看看