Measure time intervals using System.currentTimeMillis()
Well, what’s wrong with a common practice of measuring elapsed time in the code like this:
long startTime = System.currentTimeMillis(); // ... long elapsedTime = System.currentTimeMillis() - startTime;
The approach is based on an intuitive assumption that the values returned by
currentTimeMillis() (in general, the current system time expressed as a number of milliseconds since midnight, January 1, 1970 UTC) grow smoothly and always are greater in the future than in the past. This is not always the case.
A simple example when this assumption fails is adjusting the system clock. On the most of the modern systems, correction of the clock is performed automatically by polling a value from the NTP server in a specific period of time. If this correction happens in the middle of your operation, the measured time interval will be wrong or even negative. Note that the typical computer clocks have an error in tens or even hundreds of milliseconds per hour that means that the correction offset will be up to few seconds if it is performed once a day.
It is safer to use the
System.nanoTime() method which does not depend on a system clock, so it’s guaranteed that its value grows smoothly from the past to the future:
long startTime = System.nanoTime(); // ... long elapsedTime = (System.nanoTime() - startTime) / 1000000; // ms
And remember that the
nanoTime values has nothing to do with any real absolute time, so don’t try to use it for the Date objects, for instance.