簡體   English   中英

如何在Java 8中使用Date API實現精確的納秒精度

[英]How to achieve exact nanosecond precision using Date API in Java 8

我們試圖獲得具有9個精度值的精確nanoSeconds以捕獲時間。

使用Java 8,我們可以實現如下所述。

@Test
public void testNanoClock() throws InterruptedException{
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
              .appendInstant(9).toFormatter();
       for (int i=0; i<10; i++) {
       final Clock clock = new NanoClock();
       log.info(formatter.format(clock.instant()));
       Thread.sleep(200);
       }
}

Overriden instant方法如下

@Override
public Instant instant() {
  return initialInstant.plusNanos(getSystemNanos() - initialNanos);
}

下面給出了該類的完整實現。

public class NanoClock extends Clock {

    private final Clock clock;

    private final long initialNanos;

    private final Instant initialInstant;

    public NanoClock() {
        this(Clock.systemUTC());
    }

    public NanoClock(final Clock clock) {
        this.clock = clock;
        initialInstant = clock.instant();
        initialNanos = getSystemNanos();
    }

    @Override
    public ZoneId getZone() {
        return clock.getZone();
    }

    @Override
    public Clock withZone(ZoneId zone) {
        return new NanoClock(clock.withZone(zone));
    }

    @Override
    public Instant instant() {
        return initialInstant.plusNanos(getSystemNanos() - initialNanos);
    }

    private long getSystemNanos() {
        return System.nanoTime();
    }
}

通過使用上面的代碼,我們可以在9精度值下實現納秒時間:

2017-10-08T16:45:45.232000378Z

但在這種情況下,微秒將為0(零)。

如何在沒有0(零)的情況下實現精確的納秒時間和9個精度值? 怎么鍛煉?

您的代碼在循環中創建了一個新的NanoClock實例。 initialNanos每次重置initialInstantinitialNanos ,因此您永遠無法看到nanos的效果。 要完成這項工作,您需要將時鍾移出循環,可能是靜態常量。

您還應該知道,隨着時間的推移,這個時鍾可能會偏離實時,因為System.currentTimeMillis()System.nanoTime()是從操作系統中的不同時鍾源派生的,並且用於不同的目的(前者是日歷日期/牆壁時間 ,后者是經過的時間 )。 因此,您實際上是在測量自創建時鍾以來經過的時間(在一天中,兩者之間可能存在一些偏差)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM