The Answer by Leigh is correct.
java.time
Java 8 and later has the java.time framework built in.
An Instant
is a moment on the timeline in UTC with nanosecond resolution (up to 9 digits of a decimal fraction of a second). The now method grabs the current date-time moment.
Instant now = Instant.now();
2016-03-12T04:29:39.123Z
You can calculate the elapsed time between a pair of Instant
objects as a Duration. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.
Duration duration = Duration.between( startInstant , stopInstant );
The default output of Duration::toString is in standard ISO 8601 format. You can also ask for a total count of nanoseconds (toNanos) or milliseconds (toMillis), as well as other amounts.
Java 8
In Java 8, fetching the current moment resolves only to millisecond resolution (up to 3 digits of a decimal fraction of a second). So while the java.time classes can store nanoseconds they can only determine the current moment with milliseconds. This limitation is due to a legacy issue (the default Clock implementation uses System.currentTimeMillis()).
Java 9
In Java 9 and later, the default Clock
implementation can determine the current moment in up to nanosecond resolution. Actually doing so depends on the fineness of your computer’s clock hardware.
See this OpenJDK issue page for more info: Increase the precision of the implementation of java.time.Clock.systemUTC()
Micro Benchmark
If your purpose is benchmarking, be sure to look at other Questions such as:
- How do I write a correct micro-benchmark in Java?
- Create quick/reliable benchmark with java?
Frameworks are available to assist with short-duration benchmarking.