gpt4 book ai didi

java - 我可以从 System.nanoTime 合理预期的最差分辨率是多少?

转载 作者:IT王子 更新时间:2023-10-29 00:07:06 26 4
gpt4 key购买 nike

我正在编写的软件需要微秒分辨率或更好的时间戳。

我打算使用 System.currentTimeMillis结合System.nanoTime有点像这样,尽管它只是一个粗略的代码草图:

private static final long absoluteTime = (System.currentTimeMillis() * 1000 * 1000);
private static final long relativeTime = System.nanoTime();

public long getTime()
{
final long delta = System.nanoTime() - relativeTime;
if (delta < 0) throw new IllegalStateException("time delta is negative");
return absoluteTime + delta;
}

nanoTime 的文档说:

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().

所以它并没有给我们保证比毫秒更好的分辨率。

再深入一点,在 nanoTime 的幕后(可以预见这是一种本地方法):

  • Windows 使用 QueryPerformanceCounter API promise 不到 1 微秒的分辨率非常好。

  • Linux 使用 clock_gettime带有标志以确保该值是单调但不 promise 分辨率。

  • Solaris 与 Linux 相似

  • 来源没有提及 OSX 或基于 Unix 的操作系统如何处理此问题。

( source )

我看到一些模糊的暗示,它“通常”具有微秒分辨率,例如 this answer关于另一个问题:

On most systems the three least-significant digits will always be zero. This in effect gives microsecond accuracy, but reports it at the fixed precision level of a nanosecond.

但没有来源,“通常”这个词非常主观。

问题:在什么情况下nanoTime 可能会返回分辨率低于微秒的值?例如,一个主要的操作系统版本可能不支持它,或者需要一个可能不存在的特定硬件功能。如果可以,请尽量提供来源。


我使用的是 Java 1.6,但如果对这个问题有实质性好处,我升级的机会很小。

最佳答案

Question: Under what circumstances might nanoTime return a value whose resolution is worse than microseconds? What operating systems, hardware, JVMs etc. that are somewhat commonly used might this affect? Please try to provide sources if you can.

要求列出违反该约束的所有可能情况的详尽列表似乎有点过分,没有人知道您的软件将在哪些环境下运行。但要证明它会发生,请参阅此 blog post by aleksey shipilev ,他描述了一个案例,由于争用,纳秒时间在 Windows 机器上变得不如微秒准确(就其自身的延迟而言)。

另一种情况是在以非常粗略的方式模拟硬件时钟的 VM 下运行的软件。

由于特定于平台和硬件的行为,规范故意含糊不清。

一旦您确认所使用的硬件和操作系统确实提供了您所需要的并且虚拟机通过了必要的功能,您就可以“合理地期望”微秒精度。

关于java - 我可以从 System.nanoTime 合理预期的最差分辨率是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43940071/

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