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 Answers
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.
-
11I don't think daylight savings time affects currentTimeMillis(). It'd defined in terms of UTC. – Mr. Shiny and New 安宇 Oct 27 '08 at 15:42
-
@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 Oct 27 '08 at 16:26
-
Is System.nanoTime() resistant to CPU frequency changes too? – akarnokd Jun 26 '09 at 18:04
-
@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 Nov 23 '09 at 18:46
-
2See a little more detail on this in my answer to a different instance of this question which was closed as a duplicate: http://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java/1776053#1776053 – Kevin Bourrillion Nov 29 '11 at 16:14
This is some sample code.
long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();
System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");

- 136,852
- 53
- 295
- 323
-
My edit comment was "Fix method name "currentTimeMilis" -> "currentTimeMillis". Makes code copy/pasteble. (FWIW)" But couldn't find 5 more chars to edit :( – Diederik Oct 01 '12 at 11:18
-
I don't think that will work if, during your "Run some code", the machine is Windows 10 or greater and goes into S3 sleep during a Thread.sleep(). See: http://stackoverflow.com/questions/29394222/java-thread-sleep-on-windows-10-stops-in-s3-sleep-status – Dale May 12 '16 at 01:43
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

- 8,381
- 3
- 28
- 45
-
Updated link: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html – nasch Nov 02 '16 at 23:49
The Answer by Leigh is correct.
java.time
Java 8 and later has the java.time framework built in.
An Instant
is a moment on the timeline in UTC with nanosecond resolution (up to 9 digits of a decimal fraction of a second). The now
method grabs the current date-time moment.
Instant now = Instant.now();
2016-03-12T04:29:39.123Z
You can calculate the elapsed time between a pair of Instant
objects as a Duration
. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.
Duration duration = Duration.between( startInstant , stopInstant );
The default output of Duration::toString
is in standard ISO 8601 format. You can also ask for a total count of nanoseconds (toNanos
) or milliseconds (toMillis
), as well as other amounts.
Java 8
In Java 8, fetching the current moment resolves only to millisecond resolution (up to 3 digits of a decimal fraction of a second). So while the java.time classes can store nanoseconds they can only determine the current moment with milliseconds. This limitation is due to a legacy issue (the default Clock
implementation uses System.currentTimeMillis()
).
Java 9
In Java 9 and later, the default Clock
implementation can determine the current moment in up to nanosecond resolution. Actually doing so depends on the fineness of your computer’s clock hardware.
See this OpenJDK issue page for more info: Increase the precision of the implementation of java.time.Clock.systemUTC()
Micro Benchmark
If your purpose is benchmarking, be sure to look at other Questions such as:
Frameworks are available to assist with short-duration benchmarking.

- 1
- 1

- 303,325
- 100
- 852
- 1,154
java.lang.System.currentTimeMillis()
or java.lang.System.nanoTime()
ought to work to measure elapsed time.

- 136,852
- 53
- 295
- 323

- 524,688
- 99
- 697
- 795
-
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 Oct 27 '08 at 02:13
-
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. – akarnokd Jun 26 '09 at 18:09
Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:
public class StopWatch {
// Constructor
public StopWatch() {
}
// Public API
public void start() {
if (!_isRunning) {
_startTime = System.nanoTime();
_isRunning = true;
}
}
public void stop() {
if (_isRunning) {
_elapsedTime += System.nanoTime() - _startTime;
_isRunning = false;
}
}
public void reset() {
_elapsedTime = 0;
if (_isRunning) {
_startTime = System.nanoTime();
}
}
public boolean isRunning() {
return _isRunning;
}
public long getElapsedTimeNanos() {
if (_isRunning) {
return System.nanoTime() - _startTime;
}
return _elapsedTime;
}
public long getElapsedTimeMillis() {
return getElapsedTimeNanos() / 1000000L;
}
// Private Members
private boolean _isRunning = false;
private long _startTime = 0;
private long _elapsedTime = 0;
}

- 454
- 5
- 12
-
I'd suggest adding convenience methods for getting seconds value and a constructor with boolean flag which will allow the stopwatch to start immediately. At least that's what I needed, after I used your class:) – Dariusz Aug 07 '13 at 08:42