简体   繁体   中英

Fastest way to get nanos unix epoch time in Java

I currently do this to successfully get the current epoch time in nanos:

Instant inst = Instant.now();
long time = inst.getEpochSecond();
time *= 1000000000l;
time += inst.getNano();

However, it's a bit too slow for my use case, taking around 1us each call after the JVM has warmed up.

Is there a faster way to do it?

I'm happy with a solution that gives me the microseconds since epoch, as long as it's faster than the above.

What may work is to run:

long n1 = System.nanoTime();
long m = System.currentTimeMillis();
long n2 = System.nanoTime();

a number of times until the difference between n1 and n2 is less than the resolution you want (it's about 400 ns on my PC after a couple of iterations).

You can then use the difference between n1 (or n2 or an average of the 2...) and m * 1e6 as an offset that you need to add to System.nanoTime() to get the current epoch nanos.

Disclaimer:

  • System.nanoTime doc explicitly states that the resolution is at least that of System.currentTimeMillis() , which may be > 1 ms. So no guarantee that you will get microsecond resolution.
  • Corollary: this probably doesn't work in all environments (you may never get n2-n1 small enough - or it may be 0 just because the resolution of your system is too low).
  • System.nanoTime() may be out of sync over long periods - so this is a trade off between precision and performance.
  • You also need to account for possible arithmetic overflow.

See also: Current time in microseconds in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM