• Windows系统时间会偶尔自动回拨吗?


    Spring boot 项目 通过日志记录插入sql操作用时

    long start2 = System.currentTimeMillis();
    getDao().batchInsert(batchList);
    long end2 = System.currentTimeMillis();
    log.info("Save {} data 2 DB successfully took time: {}", getDescName(), (end2 - start2));    

    怎么查看日志发现有用时为负数的情况呢?

    2019-05-16 14:41:04.420  INFO 3324 --- [ave2db-thread-2] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 DB batch size: 416
    2019-05-16 14:41:03.152  INFO 3324 --- [ave2db-thread-2] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 DB successfully took time: -1268
    

    怎么用时-1268毫秒呢? Windows系统的时间偶尔会自动回拨吗?

    正常情况下应该很少发生吧.

    通常自动更新时间时有可能产生这个问题

    按照jdk的文档计算时差不建议使用System.currentTimeMillis()

    你可以看下说明.System.nanoTime()是jdk推荐的方式,即使时间回拨了也不受影响,它是从开机开始计算的时间.

    而且它建议的时间差是做减法而不是比大小.

    /**
    long java.lang.System.nanoTime()
    

    Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

    This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

    This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

    Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

    The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

    For example, to measure how long some code takes to execute:
    long startTime = System.nanoTime();
    // ... the code being measured ...
    long estimatedTime = System.nanoTime() - startTime;

    To compare two nanoTime values
    long t0 = System.nanoTime();
    ...
    long t1 = System.nanoTime();
    one should use t1 - t0 < 0, not t1 < t0, because of the possibility of numerical overflow.Returns:the current value of the running Java Virtual Machine's high-resolution time source, in nanosecondsSince:1.5
    **/

    原文地址:https://www.oschina.net/question/1175066_2306338

  • 相关阅读:
    Github markdown页面内跳转
    github gist 无法访问
    Install pyaudio on Ubuntu
    删除链表的倒数第N个节点
    电话号码的字母组合
    最长公共前缀
    盛最多水的容器
    字符串转化整数与回文数
    Z 字形变换
    LeetCode1-5题
  • 原文地址:https://www.cnblogs.com/jpfss/p/11507584.html
Copyright © 2020-2023  润新知