Java8的java.time.Instant以“纳秒分辨率”存储,但是使用Instant.now()只能提供毫秒级的分辨率...
Instant instant = Instant.now();
System.out.println(instant);
System.out.println(instant.getNano());结果...
2013-12-19T18:22:39.639Z
639000000我怎样才能得到一个值为'now',但分辨率为纳秒的Instant?
发布于 2016-07-29 19:48:06
虽然默认的Java时钟不提供纳秒精度,但您可以将其与Java8功能结合起来,以纳秒精度测量时间差,从而创建实际的纳秒时钟。
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():
final Clock clock = new NanoClock();
final Instant instant = Instant.now(clock);
System.out.println(instant);
System.out.println(instant.getNano());尽管即使您每次都重新创建NanoClock实例,此解决方案也可能有效,但最好始终使用在代码早期初始化的存储时钟,然后在需要的地方使用它。
发布于 2013-12-20 02:39:28
如果你得到了毫秒级的分辨率,你可以认为自己很幸运。
Instant可能会模拟时间到纳秒精度,但对于实际分辨率,它取决于底层操作系统实现。例如,在Windows上,分辨率相当低,大约为10ms。
这与System.nanoTime()相比,它以微秒为单位提供分辨率,但不能提供绝对的时钟时间。显然,已经有了一个折衷方案来给你这样的分辨率,距离纳秒还有三个数量级。
发布于 2013-12-20 02:42:21
所以我在这里花了一些时间研究Javadoc:
http://download.java.net/jdk8/docs/api/java/time/Instant.html
看起来您应该能够执行以下操作:
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也就是说,其他回答者提出了一个很好的观点,即很难获得精确的纳秒时间,因为计算机通常没有能力跟踪时间到那个分辨率
https://stackoverflow.com/questions/20689055
复制相似问题