package tools; import java.util.ArrayList; /* *@author Michael Diamond - DigitalGemstones.com *@version 1.1.0 (First public release) *This class was written by Michael Diamond and DigitalGemstones.com ©2007,2011 *It is released under the GPL 3. Details can be found at *http://www.DigitalGemstones.com/license.php * *This class is a self-contained stopwatch for timing operations in seconds in Java. *It has all the functionality of a generic stopwatch (Start, Stop, Pause, Resume, Reset, and Duration) *Except for time formatting - if you wish for measurments in anything other than seconds, you will need *to format the return value of stop() or duration(). */ public class Timer { private long startTime = 0; private long currentDuration = 0; private long endTime = 0; private boolean paused = false; private ArrayList laps = new ArrayList(); // Starts the Timer public void start() { startTime = curTime(); paused = false; } // Stops the Timer and returns the elapsed time since start() in seconds public double stop() { endTime = curTime(); double returnValue = ((endTime - startTime) + currentDuration) / 1000.0; reset(); return returnValue; } // Stops the Timer and outputs the elapsed time since start() in seconds, preceded by the output string public void stop(String output) { endTime = System.currentTimeMillis(); System.out.println(output + ((endTime - startTime) + currentDuration) / 1000.0); reset(); } // Pauses the Timer public void pause() { if(!paused) { currentDuration += curTime() - startTime; paused = true; } else { System.out.println("The Timer is already paused. Resetting..."); reset(); } } // Resumes a paused timer public void resume() { if(paused) { startTime = curTime(); paused = false; } else { System.out.println("The Timer was not paused. Resetting..."); reset(); } } // Resets the Timer public void reset() { startTime = currentDuration = endTime = 0; laps = new ArrayList(); paused = false; } // Returns the current value of the Timer public double duration() { if(paused) return currentDuration / 1000.0; else return (curTime() - startTime + currentDuration) / 1000.0; } // Logs the current time to an array list if not paused public void lap(){ if(!paused) laps.add(duration()); } // Gets the laps logged by this timer so far public ArrayList getLaps(){ return new ArrayList(laps); } // Returns the current time in miliseconds public static long curTime() { return System.currentTimeMillis(); } }