Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current time in microseconds in java

Tags:

java

timestamp

On a Unix system, is there a way to get a timestamp with microsecond level accuracy in Java? Something like C's gettimeofday function.

like image 965
Seth Avatar asked Nov 11 '09 00:11

Seth


People also ask

How to get current microseconds in Java?

No, Java doesn't have that ability. It does have System. nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) precision.

How do you measure microseconds?

To convert a microsecond measurement to a second measurement, divide the time by the conversion ratio. The time in seconds is equal to the microseconds divided by 1,000,000.

How long is a microsecond?

A microsecond (us or Greek letter mu plus s) is one millionth (10 -6 ) of a second. For comparison, a millisecond (ms or msec) is one thousandth of a second and is commonly used in measuring the time to read to or write from a hard disk or a CD-ROM player or to measure packet travel time on the Internet.

How are nanoseconds represented in Java?

System. nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.


2 Answers

No, Java doesn't have that ability.

It does have System.nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) precision.

Note that the JavaDoc says that whilst this provides nanosecond precision, that doesn't mean nanosecond accuracy. So take some suitably large modulus of the return value.

like image 181
AlBlue Avatar answered Oct 22 '22 09:10

AlBlue


tl;dr

Java 9 and later: Up to nanoseconds resolution when capturing the current moment. That’s 9 digits of decimal fraction.

Instant.now()    

2017-12-23T12:34:56.123456789Z

To limit to microseconds, truncate.

Instant                // Represent a moment in UTC.  .now()                 // Capture the current moment. Returns a `Instant` object.  .truncatedTo(          // Lop off the finer part of this moment.      ChronoUnit.MICROS  // Granularity to which we are truncating.  )                      // Returns another `Instant` object rather than changing the original, per the immutable objects pattern.  

2017-12-23T12:34:56.123456Z

In practice, you will see only microseconds captured with .now as contemporary conventional computer hardware clocks are not accurate in nanoseconds.

Details

The other Answers are somewhat outdated as of Java 8.

java.time

Java 8 and later comes with the java.time framework. These new classes supplant the flawed troublesome date-time classes shipped with the earliest versions of Java such as java.util.Date/.Calendar and java.text.SimpleDateFormat. The framework is defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.

The classes in java.time resolve to nanoseconds, much finer than the milliseconds used by both the old date-time classes and by Joda-Time. And finer than the microseconds asked in the Question.

enter image description here

Clock Implementation

While the java.time classes support data representing values in nanoseconds, the classes do not yet generate values in nanoseconds. The now() methods use the same old clock implementation as the old date-time classes, System.currentTimeMillis(). We have the new Clock interface in java.time but the implementation for that interface is the same old milliseconds clock.

So you could format the textual representation of the result of ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) to see nine digits of a fractional second but only the first three digits will have numbers like this:

2017-12-23T12:34:56.789000000Z

New Clock In Java 9

The OpenJDK and Oracle implementations of Java 9 have a new default Clock implementation with finer granularity, up to the full nanosecond capability of the java.time classes.

See the OpenJDK issue, Increase the precision of the implementation of java.time.Clock.systemUTC(). That issue has been successfully implemented.

2017-12-23T12:34:56.123456789Z

On a MacBook Pro (Retina, 15-inch, Late 2013) with macOS Sierra, I get the current moment in microseconds (up to six digits of decimal fraction).

2017-12-23T12:34:56.123456Z

Hardware Clock

Remember that even with a new finer Clock implementation, your results may vary by computer. Java depends on the underlying computer hardware’s clock to know the current moment.

  • The resolution of the hardware clocks vary widely. For example, if a particular computer’s hardware clock supports only microseconds granularity, any generated date-time values will have only six digits of fractional second with the last three digits being zeros.
  • The accuracy of the hardware clocks vary widely. Just because a clock generates a value with several digits of decimal fraction of a second, those digits may be inaccurate, just approximations, adrift from actual time as might be read from an atomic clock. In other words, just because you see a bunch of digits to the right of the decimal mark does not mean you can trust the elapsed time between such readings to be true to that minute degree.
like image 21
Basil Bourque Avatar answered Oct 22 '22 11:10

Basil Bourque