java - System.currenTimeInMillis() 与 System.nanoTime()

标签 java

我知道 System.nanoTime() 现在是在 System.currentTimeInMillis() 上测量时间的首选方法。第一个明显的原因是 nanoTime() 提供了更精确的计时,另一个原因是我读到后者受系统实时时钟调整的影响。 “受系统实时时钟影响”是什么意思?

最佳答案

在这种情况下,我发现以下博客文章摘录很有用:

If you are interested in measuring absolute time then always use System.currentTimeMillis(). Be aware that its resolution may be quite coarse (though this is rarely an issue for absolute times.)

If you are interested in measuring/calculating elapsed time, then always use System.nanoTime(). On most systems it will give a resolution on the order of microseconds. Be aware though, this call can also take microseconds to execute on some platforms.

Clocks and Timers - General Overview大卫·福尔摩斯

由于 System.currentTimeMillis() 依赖于系统 time of day 时钟,因此对时间的调整是合法的,以保持准时。

这里的调整是什么意思?以 Linux 中 CLOCK_REALTIME 的描述为例:

System-wide clock that measures real (i.e., wall-clock) time. Setting this clock requires appropriate privileges. This clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by the incremental adjustments performed by adjtime(3) and NTP.

关于java - System.currenTimeInMillis() 与 System.nanoTime(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11591000/

相关文章:

java - 放心请求不起作用

Java 难题访问 main 的参数而不传入它们

java - 调用 ArrayAdapter 中的 getView() 时

java - 为什么我缺少 else 的返回语句

java - 如何使用并行端口像开关一样工作,读取(获取)信号并在java中监听真假?

java - 您如何在 JavaServer Faces 中执行分页列表?

Java 从 JSON 文件导入 JTable

java - 在 Java 中执行 PigServer 时出错

java - Keycloak中如何根据@PathVariable或@RequestBody定义访问条件?

java - 带有 XPath 的 JDOM2 不适用于 namespace