How do I measure time elapsed in Java? [duplicate]

Unfortunately, none of the ten answers posted so far are quite right.

If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime(). You cannot use System.currentTimeMillis(), unless you don’t mind your result being wrong.

The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can’t use the one for the other purpose. The reason is that no computer’s clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there’s a process that runs and continually issues small corrections to the system clock (“wall clock”). These tend to happen often. Another such correction happens whenever there is a leap second.

Since nanoTime‘s purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis will be off — possibly even negative.

You may say, “this doesn’t sound like it would ever really matter that much,” to which I say, maybe not, but overall, isn’t correct code just better than incorrect code? Besides, nanoTime is shorter to type anyway.

Previously posted disclaimers about nanoTime usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don’t expect to time very very small intervals correctly.

Leave a Comment