views:

1179

answers:

5

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?

+7  A: 

I hope not - it's what I use when i don't use nanoTime().

David Johnstone
One gotcha (on Windows w. Sun JDK6, in any case) with `nanoTime` is that the value returned depends on the CPU core executing the thread. If the thread starts executing on one core and finishes on another core, your numbers will be somewhat off. I had code like `long start = System.nanoTime(); doIt(); long elapsedNanos = System.nanoTime() - start;` and wound up with `elapsedNanos` being negative.
gustafc
+1  A: 

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.

+1  A: 

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.

jwoolard
A: 

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())

dfa