How Do I Time Things In Java? - Javamex

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 resolution (thousanths or billionths of a second) to which the time is reported;
  • the actual granularity of measurements;
  • the time taken to make the measurement;
  • how stable the performance of the timer is;
  • whether the time reported means anything in "real life" absolute time and so can be compared across systems and used as time stamps.

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.

Tag » How To Time Things In Java