Java provides two methods to time operations, System.nanoTime() and System.currentTimeMillis(). But which one should be used in which condition? And which is more efficient?
From the first look it might seem that nanoTime() should be used because it gives more precise value of time (in nano seconds, compared to milli seconds that the other method returns). But is it always efficient on the CPU to use nanoTime? Let us look at pros and cons of using both the methods:
public static long currentTimeMillis() // Returns the current time in milliseconds.
- It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results.
- Always returns the absolute time elapsed since the epoch (number of millis since 1 Jan 1970 00:00).
- Consumes lesser clock cycles to execute (around 5-6 cpu clocks).
- Gives more accurate time, since the point of reference (the epoch) is fixed.
- Less precise. The result is somewhere between 1/1000th to 15/1000th of a second. On some machines, the resolution is even less than 50ms and can go down to upto 10ms only.
- It may give wrong results if the user changes the system time, hits a leap second or there are changes in NTP sync.
public static long nanoTime() // Returns the current value of the running JVM's high-resolution // time source, in nanoseconds.
- Highly precise. The time returned is around 1/1000000th of a second.
- The resolution is much higher than currentTimeMillis().
- The result reflected doesn’t have any fixed reference point. According to Java documentation,
The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative).
- Less accurate. This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.
- Depending on the system, it can take more than 100 cpu cycles to execute.
- Not thread safe. May return erroneous results if used between more than one threads.
Let’s see a working example to compare the results of these two functions:
Time taken in nano seconds: 2519657 Time taken in milli seconds: 3
In conclusion, System.nanoTime() can/must be used whenever tasks of high precisions are to be performed, because it might seem that milli seconds is enough precision but for applications requiring fast performances (like games) nanoTime() will give much better results.
However, it should be avoided whenever possible due to computational overheads and risks related to thread safety, in which case currentTimeMillis() is to be used.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.