0

I would like to get the current time in microseconds since epoch with as much accuracy as possible, and in a monotonic way.

Does anyone have experience with that? I tried the following two approaches, but the first one is inaccurate and not monotonic, and I'm not sure the second won't have a weird behaviour when time jumps from one millisecond to the next.

(I'm working with Kotlin so I'm open to any kind of Java solution)

fun nowInMicrosSinceEpoch() : Long {
    val now = Instant.now()
    return now.toEpochMilli() * 1000L + (now.getNano().toLong() / 1000L)
}
fun nowInMicrosSinceEpoch() : Long {
    return (System.currentTimeMillis() * 1000L) + (System.nanoTime() % 1_000_000L / 1000L)
}
Ben
  • 317
  • 3
  • 12
  • 3
    `System.nanoTime()` has nothing whatsoever to do with real time, so do not use that. – Andreas Feb 01 '19 at 23:24
  • I know it's meant to measure intervals... Is there a way to get something accurate? – Ben Feb 01 '19 at 23:26
  • The only way to absolute guarantee accurate, monotonic time is to call a time service. See [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol) (Network Time Protocol). Anything else depends on the computers time, and it can be changed, so no guarantee of monotonic values. Java's time values all derived from the computer time. – Andreas Feb 01 '19 at 23:26
  • Thank you! Actually, I do not need anything perfectly exact, only something monotonic and close to the real "absolute" time given by an atomic clock. This code will always run on the same server, so I only need the data it writes to be consistent. – Ben Feb 01 '19 at 23:31
  • 1
    Added new duplicate link saying that you get nano-second precision from `Instant.now()` if you use Java 9 (or later), so **use Java 11**, since Java 9 and 10 are both EOL already. – Andreas Feb 01 '19 at 23:44
  • https://stackoverflow.com/questions/54228304/delay-accuracy-issues-weird-behavior-of-job-scheduler - Instant.now() is not monotonic... – Ben Feb 01 '19 at 23:56
  • It is as monotonic as the `Clock` it is using, and since they totally re-implemented the `Clock` in Java 9 for extended precision ([JDK-8068730](https://bugs.openjdk.java.net/browse/JDK-8068730)), how would you know from some obscure, unverified test done in Java 8? – Andreas Feb 02 '19 at 00:01
  • 1
    Let me re-phrase "obscure, unverified test" to "invalid code". Added answer to that question explaining why. Even in Java 8, `Instant.now()` *is* monotonic. – Andreas Feb 02 '19 at 00:26

0 Answers0