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 after the action is taken? Is there a better alternative?
views:
1179answers:
5Before 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.
Take a look at this:
http://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java
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
())