Timing Is Everything
by Byron Lee aka Technobard
One of the most common questions I'm asked these days is "how long did it take to run" or the related "how long will it take to run". In every environment I work in, sooner or later I get around to figuring out how to do timings. In Java, I was hoping for something as simple as a stopwatch. You know, ready, set, CLICK........and..CLICK. 3.65 seconds..or something like that. Sometimes I want minutes, sometimes I want milliseconds. It all depends. And while there are other, more advanced features I'd like to have, the simple solution covers at least 80% of what I really need.
Let's take a look at the StopWatch class and a "main" method to test it.
CLICK...
Code:
import java.util.*;
public class StopWatch {
Calendar startCal;
Calendar endCal;
TimeZone tz = TimeZone.getTimeZone("CST");
/** Creates a new instance of StopWatch */
public StopWatch() {
}
public StopWatch(String tzoneStr) {
tz = TimeZone.getTimeZone(tzoneStr);
}
// Start the stopwatch
public void start() {
startCal = Calendar.getInstance(tz);
}
// Stop the stopwatch
public void end() {
endCal = Calendar.getInstance(tz);
}
// Measure the elapsed time in different units
public double elapsedSeconds() {
return (endCal.getTimeInMillis() - startCal.getTimeInMillis())/1000.0;
}
public long elapsedMillis() {
return endCal.getTimeInMillis() - startCal.getTimeInMillis();
}
public double elapsedMinutes() {
return (endCal.getTimeInMillis() - startCal.getTimeInMillis())/(1000.0 * 60.0);
}
public static void main (String [] args) {
StopWatch sw = new StopWatch();
sw.start(); // capture start time
try {
Thread.sleep(5000); // sleep for 5 seconds
}catch (Exception e) {
System.out.println(e);
System.exit(1);
}
sw.end(); // capture end time
System.out.println("Elapsed time in minutes: " + sw.elapsedMinutes());
System.out.println("Elapsed time in seconds: " + sw.elapsedSeconds());
System.out.println("Elapsed time in milliseconds: " + sw.elapsedMillis());
}
} // end of StopWatch class
The StopWatch class is fairly simple. It contains two Calendar objects: "startCal" and "endCal". Each Calendar object contains the date and time to the millisecond at the time each instance is created. A call to Calendar.getInstance() returns a new Calendar object. Take a look at the start() and end() methods. Once these are set, the remaining methods calculate elapsed time in various units.
CLICK. Time to go.