There are two standard ways to time operations in Java: System.currentTimeMillis() and System.nanoTime(). Depending on your JVM, there may be other mechanisms available, but these are generally the two standard ways to time things in Java. On this page, we look at the differences between System.currentTimeMillis() and System.nanoTime() and when to use each.
Broadly, either of these calls can serve a similar function to time an operation, using the familiar and logical pattern:
However, the two timing calls differ in:
The following table summarises System.currentTimeMillis() and System.nanoTime() with respect to these features.
System.currentTimeMillis | System.nanoTime() | ||
---|---|---|---|
Theoretical resolution | 1/1000th of a second | 1/1000,000,000th of a second | |
Typical granularity in practice | Either 1/1000th of a second, or 10 or 15 1/1000ths of a second, depending on system | Around 1/1000,000th of a second (1,000 nanos) | |
Time taken to read | A few clock cycles | 100+ clock cycles | |
Stability | Unstable under Windows: granularity subject to variation. | Stable on a given system. | |
Absolute time? | Yes: value reported is number of millis since 1 Jan 1970 00:00 | No: zero does not necessarily represent any particular reference point. |