java - System.nanotime运行缓慢?

标签 java nanotime

我的一个 friend 向我展示了他所做的一些事情,我无法解释这是如何发生的:他正在使用 System.nanotime 来计时,并且每秒都会向用户提供更新告诉我们已经过去了多少时间(对于该部分,它是 Thread.sleep(1000)),并且它似乎花了很长时间(等待 10 秒的事情大约需要 3 分钟才能完成)。我们尝试使用毫秒来查看已经过去了多少时间:它打印每秒过去了多少纳米时间,我们看到每一秒,纳米时间每秒移动大约 40-50 毫秒。

我检查了与 System.nanotime 和 Java 相关的错误,但似乎我能找到的唯一涉及纳米时间的东西突然 greatly increasing and then stopping 。我还浏览了this blog entry基于我在另一个问题中读到的内容,但没有任何可能导致它的原因。

显然,可以通过使用毫秒来解决这种情况;有很多解决方法,但我很好奇的是,除了系统时钟的硬件问题之外,是否还有其他问题,或者至少是CPU拥有的最准确的时钟(因为这就是System.nanotime似乎使用的)这可能会导致它像这样运行缓慢?

long initialNano = System.nanoTime();
long initialMili = System.currentTimeMillis();
//Obviously the code isn't actually doing a while(true), 
//but it illustrates the point
while(true) {
    Thread.sleep(1000);
    long currentNano = System.nanoTime();
    long currentMili = System.currentTimeMillis();
    double secondsNano = ((double) (currentNano - initialNano))/1000000000D;
    double secondsMili = ((double) (currentMili - initialMili))/1000D;
    System.out.println(secondsNano);
    System.out.println(secondsMili);
}

SecondsNano 将打印类似 0.04 的内容,而 SecondsMili 将打印非常接近 1 的内容。

似乎已在 Sun's bug database 报告了该行的错误,但他们将其作为重复项关闭,但他们的链接不会指向现有的错误。它似乎非常特定于系统,所以我越来越确定这是一个硬件问题。

最佳答案

... he was using a System.nanotime to cause the program to wait before doing something, and ...

你能给我们看一些代码来准确地演示他在做什么吗?是不是某种奇怪的繁忙循环,如下所示:

long t = System.nanoTime() + 1000000000L;
while (System.nanoTime() < t) { /* do nothing */ }

如果是,那么这不是让程序暂停一段时间的正确方法。使用 Thread.sleep(...) 来使程序等待指定的毫秒数。

关于java - System.nanotime运行缓慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567970/

相关文章:

java - 如何使用 2 种不同类型的 HashMap 定义 2 个构造函数?

java Swing : add custom graphical button to JTree item

java - 如何从double中获取整数的小数部分?

Java - 将纳秒转换为 HH/MM/SS

java - strace Java 小程序

java - .toNanos() 方法无法正常工作

java - Centos 7,System.nanoTime 比 Windows 慢 400 倍

java - 用递归实现 Stack 的 Pop 方法

java - Apache Storm : storm-kafka-monitor script throws exception

Android - 测量通过 Intent 打开 Activity 与收到结果之间的时间