java - System.currentTimeMillis 与 System.nanoTime

标签 java timer time-precision

准确度与精度精度

我想知道的是,在更新游戏中对象的位置时,是否应该使用 System.currentTimeMillis() 还是 System.nanoTime()?它们的运动变化与自上次调用以来耗时成正比,我希望尽可能精确。

我了解到不同操作系统之间存在一些严重的时间分辨率问题(即 Mac/Linux 的分辨率几乎为 1 毫秒,而 Windows 的分辨率为 50 毫秒??)。我主要在 Windows 上运行我的应用程序,50 毫秒的分辨率似乎相当不准确。

还有比我列出的两个更好的选择吗?

有什么建议/意见吗?

最佳答案

如果您只是寻求极其精确的耗时测量,请使用System.nanoTime()System.currentTimeMillis() 将为您提供自纪元以来最准确的可能耗时(以毫秒为单位),但 System.nanoTime() 为您提供相对于某个任意点的纳秒级精确时间。

来自 Java 文档:

public static long 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 origin 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.

例如,测量某些代码的执行时间:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

另请参阅:JavaDoc System.nanoTime()JavaDoc System.currentTimeMillis()了解更多信息。

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

相关文章:

javascript - 重置 jQuery 轮播中的计时器

c# - C# 和 SQL Server 中的 DateTimeOffset 解析

java - 如何使用数组列表的不同子类型重载构造函数?

java - 如何在Spring中使用Template Hibernate保存继承的类

java - 尝试使用原始套接字发送 GET 请求时收到 301

javascript - 页面加载定时器上的红绿灯

java - 创建字符串的正则表达式

python - 如何检查键盘按钮是否收到垃圾邮件并在再次按下之前添加冷却时间

Java 计时,System.nanoTime() 比 System.currentTimeMillis() 更胜一筹,但它会持续 sleep 吗?

splunk - 在 Splunk 查询中对 "earliest"使用亚秒精度