java - Windows XP 上的 System.nanoTime()

标签 java time

我刚刚找到System.currentTimeMillis is not accurate在 Windows XP 上,现在我尝试使用相同的代码 System.nanoTime()

由于1ms = 1,000,000ns,所以我认为结果应该是15,000,000ns,但事实并非如此。

查看示例代码:

public class NanoTime {
    public static void main(String[] args) {
        long start = 0;
        long end = 0;
        while (true) {
            if (start == 0) {
                start = System.nanoTime();
            } else {
                long current = System.nanoTime();
                if (current != start) {
                    end = current;
                    break;
                }
            }
        }
        System.out.println("The time interval of your OS: " + (end - start) + "ns");
    }
}

结果是:

The time interval of your OS: 655ns

看起来它比 System.currentTimeMillis() 好得多。但为什么?我们能相信这个结果吗?

最佳答案

如果您的 Windows XP 有 SP3,那么您可以相信这个结果...在 Windows 上,JVM 使用 QueryPerformanceCounter/QueryPerformanceFrequency内部实现 nanoTime() code> API 基本上位于 HAL(硬件抽象层)中,并使用一些相当准确的 CPU 内部间隔指令...它仅适用于间隔测量不适合时间处理...

有关更详细的描述,请参阅 http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clockshttp://juliusdavies.ca/posix_clocks/clock_realtime_linux_faq.html

编辑 - 根据评论:

上面提到的函数是在调用 nanoTime 时由 JVM 本身内部使用的,与 JNI 完全无关 - 它们不会暴露给 Java 代码!

编辑 2 - 根据评论:

nanoTime() 是准确测量耗时的正确工具,而 currentTimeMillis 是处理绝对时间<的正确工具.

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

相关文章:

java - ZonedDateTime toString 与 ISO 8601 的兼容性

algorithm - 平衡二叉树高度的大O

java - 正则表达式解析命令行选项

java - 有点关心Java WEB START

java - 使用信号量的监控程序在java中无法按预期工作

java - 将字符串格式的日期解析为 GregorianCalendar 的最简单方法

java - JJOE64 GraphView 库

matlab - 自 "Jan 1, 0000": is this -1 BC or +1 CE? 起的序列日期号

python - 在Python中比较unix时间戳

php - mysqli计划时间错误: not added into the table