相关疑难解决方法(0)

System.currentTimeMillis vs System.nanoTime

精度与 精确

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

我读过不同的操作系统之间存在一些严重的时间分辨率问题(即Mac/Linux的分辨率几乎为1毫秒,而Windows的分辨率为50毫秒).我主要在Windows上运行我的应用程序,50ms分辨率似乎非常不准确.

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

有什么建议/意见吗?

java timer time-precision

370
推荐指数
7
解决办法
37万
查看次数

为什么我的System.nanoTime()坏了?

我和我这个时代的另一位开发人员最近从一台Core 2 Duo机器搬到了新的Core 2 Quad 9505; 两者都使用JDK 1.6.0_18运行Windows XP SP3 32位.

在这样做的时候,我们对一些时序/统计/度量聚合代码的自动单元测试很快就会失败,因为看起来似乎是从System.nanoTime()返回的荒谬值.

在我的机器上可靠地显示此行为的测试代码是:

import static org.junit.Assert.assertThat;

import org.hamcrest.Matchers;
import org.junit.Test;

public class NanoTest {

  @Test
  public void testNanoTime() throws InterruptedException {
    final long sleepMillis = 5000;

    long nanosBefore = System.nanoTime();
    long millisBefore = System.currentTimeMillis();

    Thread.sleep(sleepMillis);

    long nanosTaken = System.nanoTime() - nanosBefore;
    long millisTaken = System.currentTimeMillis() - millisBefore;

    System.out.println("nanosTaken="+nanosTaken);
    System.out.println("millisTaken="+millisTaken);

    // Check it slept within 10% of requested time
    assertThat((double)millisTaken, Matchers.closeTo(sleepMillis, sleepMillis * 0.1));
    assertThat((double)nanosTaken, Matchers.closeTo(sleepMillis * 1000000, sleepMillis * 1000000 …
Run Code Online (Sandbox Code Playgroud)

java timestamp nanotime

11
推荐指数
1
解决办法
5900
查看次数

标签 统计

java ×2

nanotime ×1

time-precision ×1

timer ×1

timestamp ×1