首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有纳秒分辨率的Java8 Instant.now()?

具有纳秒分辨率的Java8 Instant.now()?
EN

Stack Overflow用户
提问于 2013-12-20 02:29:39
回答 5查看 47.3K关注 0票数 27

Java8的java.time.Instant以“纳秒分辨率”存储,但是使用Instant.now()只能提供毫秒级的分辨率...

代码语言:javascript
复制
Instant instant = Instant.now();
System.out.println(instant);
System.out.println(instant.getNano());

结果...

代码语言:javascript
复制
2013-12-19T18:22:39.639Z
639000000

我怎样才能得到一个值为'now',但分辨率为纳秒的Instant?

EN

回答 5

Stack Overflow用户

发布于 2016-07-29 19:48:06

虽然默认的Java时钟不提供纳秒精度,但您可以将其与Java8功能结合起来,以纳秒精度测量时间差,从而创建实际的纳秒时钟。

代码语言:javascript
复制
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 Instant instant()
    {
        return initialInstant.plusNanos(getSystemNanos() - initialNanos);
    }

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

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

使用它很简单:只需向Instant.now()提供额外的参数,或者直接调用Clock.instant():

代码语言:javascript
复制
    final Clock clock = new NanoClock();   
    final Instant instant = Instant.now(clock);
    System.out.println(instant);
    System.out.println(instant.getNano());

尽管即使您每次都重新创建NanoClock实例,此解决方案也可能有效,但最好始终使用在代码早期初始化的存储时钟,然后在需要的地方使用它。

票数 20
EN

Stack Overflow用户

发布于 2013-12-20 02:39:28

如果你得到了毫秒级的分辨率,你可以认为自己很幸运。

Instant可能会模拟时间到纳秒精度,但对于实际分辨率,它取决于底层操作系统实现。例如,在Windows上,分辨率相当低,大约为10ms。

这与System.nanoTime()相比,它以微秒为单位提供分辨率,但不能提供绝对的时钟时间。显然,已经有了一个折衷方案来给你这样的分辨率,距离纳秒还有三个数量级。

票数 18
EN

Stack Overflow用户

发布于 2013-12-20 02:42:21

所以我在这里花了一些时间研究Javadoc:

http://download.java.net/jdk8/docs/api/java/time/Instant.html

看起来您应该能够执行以下操作:

代码语言:javascript
复制
Instant inst = Instant.now();
long time = inst.getEpochSecond();
time *= 1000000000L; //convert to nanoseconds
time += inst.getNano(); //the nanoseconds returned by inst.getNano() are the nanoseconds past the second so they need to be added to the epoch second

也就是说,其他回答者提出了一个很好的观点,即很难获得精确的纳秒时间,因为计算机通常没有能力跟踪时间到那个分辨率

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20689055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档