Is there a stopwatch in Java?
On Google I only found code of stopwatches that don't work - they always return 0 milliseconds.
This code I found doesn't work and I don't see why.
public class StopWatch {
private long startTime = 0;
private long stopTime = 0;
private boolean running = false;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.stopTime = System.currentTimeMillis();
this.running = false;
}
//elaspsed time in milliseconds
public long getElapsedTime() {
long elapsed;
if (running) {
elapsed = (System.currentTimeMillis() - startTime);
} else {
elapsed = (stopTime - startTime);
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000);
} else {
elapsed = ((stopTime - startTime) / 1000);
}
return elapsed;
}
}
currentTimeMillis()
for production, as it's tied to system date/time and is not guaranteed to be monotonous (e.g. you can get negative elapsed time). For measuring time usenanoTime()
– it's guaranteed to be monotonous and intended exactly for measuring purpose. See docs.oracle.com/javase/8/docs/api/java/lang/… – Wardwarde