How do I time things in Java?

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.

Comparison of System.currentTimeMillis() vs System.nanoTime()

Broadly, either of these calls can serve a similar function to time an operation, using the familiar and logical pattern:

  1. take the current time and store in a variable;
  2. perform the operation;
  3. repeat the call to get the current time again, and subtract from the previously stored time to determine how long the operation took.

However, the two timing calls differ in:

The following table summarises System.currentTimeMillis() and System.nanoTime() with respect to these features.

 System.currentTimeMillisSystem.nanoTime()
Theoretical resolution1/1000th of a second1/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.