Is System.currentTimeMillis() the best measure of time performance in Java? Are there any gotcha\'s when using this to compare the time before action is taken to the time af
One gotcha is that this measures real time elapsed, not CPU time - so it is very dependent on system load. This is fine if your on an otherwise free machine, but can sometimes produce interesting results if other processes are trying to do work.
This article has an intersting solution to the problem.
besides System.nanoTime()
, JMX is probably the best viable option:
java.lang.management.ManagementFactory.getThreadMXBean()
you can query current thread cpu time (measured in nano seconds but not with nano seconds precision, as for System.nanoTime
())
If you need monotonic time measurements, System.nanoTime is a better choice. System.currentTimeMillis is subject to UTC timing variations -- leap seconds, NTP updates and jitter, as well as users setting the system clock*. This can cause some spectacular failures in certain kinds of timing applications. System.nanoTime is supposed to be immune to all that.
The problems with System.nanoTime include periodic numeric overflow and long term timing inaccuracy, making System.currentTimeMillis better for longer time spans (provided that users leave the system clock alone). Note that daylight saving time and time zone changes should not affect System.currentTimeMillis.
*Windows "Sync with internet time" makes stepwise changes. This can be very disruptive, as opposed to a proper NTP client implementation that "chases" the server by adjusting the client timebase frequency.
Before Java 1.5 there was only System.currentTimeMillis. However the granularity of the value depends on the underlying operating system and may be large. On Windows XP I sometimes ended up with gaps of 20ms. I heard Linux is way better with gaps in the range of 1-2ms.
With Java 1.5 you can also use System.nanoTime. I never had problems with this one.
I hope not - it's what I use when i don't use nanoTime().
Take a look at this:
How do I time a method's execution in Java?