gpt4 book ai didi

java - System.currentTimeMillis()、new Date().getTime() 和 Calendar.getInstance().getTimeInMillis() 的准确性?

转载 作者:行者123 更新时间:2023-11-29 09:55:49 27 4
gpt4 key购买 nike

我正要在 Eclipse 中使用 System.currentTimeMillis() 时,我注意到它的 Javadoc 中出现了以下段落:

Returns the current system time in milliseconds since January 1, 1970
00:00:00 UTC. This method shouldn't be used for measuring timeouts or
other elapsed time measurements, as changing the system time can affect
the results.

所以这意味着如果我想专门维护对当前时间点的引用,我不能依赖 System.currentTimeMillis()。那么,最准确的方法是什么?这三种方法标记当前时间是否不同?

更新:我想做的是测量两个独立程序运行中两个时间点之间的差异。我担心的是,如果我使用 System.currentTimeMillis() 并且用户在第一次运行后使用系统时间,我可能会在第二次运行时得到一个奇怪的意外值。

最佳答案

您应该使用 API 文档中的 System.nanoTime():

Returns the current value of the most precise available system timer, 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 time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

关于java - System.currentTimeMillis()、new Date().getTime() 和 Calendar.getInstance().getTimeInMillis() 的准确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com