tags:

views:

2602

answers:

4

What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?

+6  A: 

java.lang.System.currentTimeMillis() or java.lang.System.nanoTime() ought to work to measure elapsed time.

tvanfosson
Keep in mind that even though those functions return values that are measured in milliseconds and nanoseconds respectively, the clock resolution may not be that high. A clock resolution of 15 ms is pretty common -- keep that in mind when timing very short events.
Adam Rosenfield
I have good experience with LockSupport.parkNanos() on Windows in terms of resolution - but that's not a candidate for a stopwatch for this question I admit.
kd304
+10  A: 

This is some sample code.

long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMilis();

System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");
jjnguy
+3  A: 

Apache Commons-Lang also has the StopWatch class suited just for your purpose. It uses System.currentTimeMillis(), so you'll still have resolution problems, but you can pause and do lap times and such. I use it as standard now for event stats.

http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/StopWatch.html

Spencer K
+16  A: 

I would avoid using System.currentTimeMillis() for measuring elapsed time. currentTimeMillis() returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.

System.nanoTime(), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.

Leigh
Good to know. I did not know that there were differences between currentTimeMillis() and nanoTime() besides resolution.
Jack Leow
I don't think daylight savings time affects currentTimeMillis(). It'd defined in terms of UTC.
Mr. Shiny and New
@Shiny: Good point on UTC - I didn't realise that. I think the main point of my response stands though, ie, currentTimeMillis() is skewed by wall-clock changes. NTP updates are another possible source of problems with currentTimeMillis().
Leigh
Is System.nanoTime() resistant to CPU frequency changes too?
kd304
@kd304, I'm sure it is; it should also be robust to the computer hibernating and waking up. If it isn't, it's a bug.
Kevin Bourrillion