001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     * 
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     * 
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.commons.lang.time;
019    
020    /**
021     * <p>
022     * <code>StopWatch</code> provides a convenient API for timings.
023     * </p>
024     * 
025     * <p>
026     * To start the watch, call {@link #start()}. At this point you can:
027     * </p>
028     * <ul>
029     * <li>{@link #split()} the watch to get the time whilst the watch continues in the background. {@link #unsplit()} will
030     * remove the effect of the split. At this point, these three options are available again.</li>
031     * <li>{@link #suspend()} the watch to pause it. {@link #resume()} allows the watch to continue. Any time between the
032     * suspend and resume will not be counted in the total. At this point, these three options are available again.</li>
033     * <li>{@link #stop()} the watch to complete the timing session.</li>
034     * </ul>
035     * 
036     * <p>
037     * It is intended that the output methods {@link #toString()} and {@link #getTime()} should only be called after stop,
038     * split or suspend, however a suitable result will be returned at other points.
039     * </p>
040     * 
041     * <p>
042     * NOTE: As from v2.1, the methods protect against inappropriate calls. Thus you cannot now call stop before start,
043     * resume before suspend or unsplit before split.
044     * </p>
045     * 
046     * <p>
047     * 1. split(), suspend(), or stop() cannot be invoked twice<br />
048     * 2. unsplit() may only be called if the watch has been split()<br />
049     * 3. resume() may only be called if the watch has been suspend()<br />
050     * 4. start() cannot be called twice without calling reset()
051     * </p>
052     * 
053     * <p>This class is not thread-safe</p>
054     * 
055     * @author Apache Software Foundation
056     * @since 2.0
057     * @version $Id: StopWatch.java 1056988 2011-01-09 17:58:53Z niallp $
058     */
059    public class StopWatch {
060    
061        // running states
062        private static final int STATE_UNSTARTED = 0;
063    
064        private static final int STATE_RUNNING = 1;
065    
066        private static final int STATE_STOPPED = 2;
067    
068        private static final int STATE_SUSPENDED = 3;
069    
070        // split state
071        private static final int STATE_UNSPLIT = 10;
072    
073        private static final int STATE_SPLIT = 11;
074    
075        /**
076         * The current running state of the StopWatch.
077         */
078        private int runningState = STATE_UNSTARTED;
079    
080        /**
081         * Whether the stopwatch has a split time recorded.
082         */
083        private int splitState = STATE_UNSPLIT;
084    
085        /**
086         * The start time.
087         */
088        private long startTime = -1;
089    
090        /**
091         * The stop time.
092         */
093        private long stopTime = -1;
094    
095        /**
096         * <p>
097         * Constructor.
098         * </p>
099         */
100        public StopWatch() {
101            super();
102        }
103    
104        /**
105         * <p>
106         * Start the stopwatch.
107         * </p>
108         * 
109         * <p>
110         * This method starts a new timing session, clearing any previous values.
111         * </p>
112         * 
113         * @throws IllegalStateException
114         *             if the StopWatch is already running.
115         */
116        public void start() {
117            if (this.runningState == STATE_STOPPED) {
118                throw new IllegalStateException("Stopwatch must be reset before being restarted. ");
119            }
120            if (this.runningState != STATE_UNSTARTED) {
121                throw new IllegalStateException("Stopwatch already started. ");
122            }
123            this.stopTime = -1;
124            this.startTime = System.currentTimeMillis();
125            this.runningState = STATE_RUNNING;
126        }
127    
128        /**
129         * <p>
130         * Stop the stopwatch.
131         * </p>
132         * 
133         * <p>
134         * This method ends a new timing session, allowing the time to be retrieved.
135         * </p>
136         * 
137         * @throws IllegalStateException
138         *             if the StopWatch is not running.
139         */
140        public void stop() {
141            if (this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
142                throw new IllegalStateException("Stopwatch is not running. ");
143            }
144            if (this.runningState == STATE_RUNNING) {
145                this.stopTime = System.currentTimeMillis();
146            }
147            this.runningState = STATE_STOPPED;
148        }
149    
150        /**
151         * <p>
152         * Resets the stopwatch. Stops it if need be.
153         * </p>
154         * 
155         * <p>
156         * This method clears the internal values to allow the object to be reused.
157         * </p>
158         */
159        public void reset() {
160            this.runningState = STATE_UNSTARTED;
161            this.splitState = STATE_UNSPLIT;
162            this.startTime = -1;
163            this.stopTime = -1;
164        }
165    
166        /**
167         * <p>
168         * Split the time.
169         * </p>
170         * 
171         * <p>
172         * This method sets the stop time of the watch to allow a time to be extracted. The start time is unaffected,
173         * enabling {@link #unsplit()} to continue the timing from the original start point.
174         * </p>
175         * 
176         * @throws IllegalStateException
177         *             if the StopWatch is not running.
178         */
179        public void split() {
180            if (this.runningState != STATE_RUNNING) {
181                throw new IllegalStateException("Stopwatch is not running. ");
182            }
183            this.stopTime = System.currentTimeMillis();
184            this.splitState = STATE_SPLIT;
185        }
186    
187        /**
188         * <p>
189         * Remove a split.
190         * </p>
191         * 
192         * <p>
193         * This method clears the stop time. The start time is unaffected, enabling timing from the original start point to
194         * continue.
195         * </p>
196         * 
197         * @throws IllegalStateException
198         *             if the StopWatch has not been split.
199         */
200        public void unsplit() {
201            if (this.splitState != STATE_SPLIT) {
202                throw new IllegalStateException("Stopwatch has not been split. ");
203            }
204            this.stopTime = -1;
205            this.splitState = STATE_UNSPLIT;
206        }
207    
208        /**
209         * <p>
210         * Suspend the stopwatch for later resumption.
211         * </p>
212         * 
213         * <p>
214         * This method suspends the watch until it is resumed. The watch will not include time between the suspend and
215         * resume calls in the total time.
216         * </p>
217         * 
218         * @throws IllegalStateException
219         *             if the StopWatch is not currently running.
220         */
221        public void suspend() {
222            if (this.runningState != STATE_RUNNING) {
223                throw new IllegalStateException("Stopwatch must be running to suspend. ");
224            }
225            this.stopTime = System.currentTimeMillis();
226            this.runningState = STATE_SUSPENDED;
227        }
228    
229        /**
230         * <p>
231         * Resume the stopwatch after a suspend.
232         * </p>
233         * 
234         * <p>
235         * This method resumes the watch after it was suspended. The watch will not include time between the suspend and
236         * resume calls in the total time.
237         * </p>
238         * 
239         * @throws IllegalStateException
240         *             if the StopWatch has not been suspended.
241         */
242        public void resume() {
243            if (this.runningState != STATE_SUSPENDED) {
244                throw new IllegalStateException("Stopwatch must be suspended to resume. ");
245            }
246            this.startTime += (System.currentTimeMillis() - this.stopTime);
247            this.stopTime = -1;
248            this.runningState = STATE_RUNNING;
249        }
250    
251        /**
252         * <p>
253         * Get the time on the stopwatch.
254         * </p>
255         * 
256         * <p>
257         * This is either the time between the start and the moment this method is called, or the amount of time between
258         * start and stop.
259         * </p>
260         * 
261         * @return the time in milliseconds
262         */
263        public long getTime() {
264            if (this.runningState == STATE_STOPPED || this.runningState == STATE_SUSPENDED) {
265                return this.stopTime - this.startTime;
266            } else if (this.runningState == STATE_UNSTARTED) {
267                return 0;
268            } else if (this.runningState == STATE_RUNNING) {
269                return System.currentTimeMillis() - this.startTime;
270            }
271            throw new RuntimeException("Illegal running state has occured. ");
272        }
273    
274        /**
275         * <p>
276         * Get the split time on the stopwatch.
277         * </p>
278         * 
279         * <p>
280         * This is the time between start and latest split.
281         * </p>
282         * 
283         * @return the split time in milliseconds
284         * 
285         * @throws IllegalStateException
286         *             if the StopWatch has not yet been split.
287         * @since 2.1
288         */
289        public long getSplitTime() {
290            if (this.splitState != STATE_SPLIT) {
291                throw new IllegalStateException("Stopwatch must be split to get the split time. ");
292            }
293            return this.stopTime - this.startTime;
294        }
295    
296        /**
297         * Returns the time this stopwatch was started.
298         * 
299         * @return the time this stopwatch was started
300         * @throws IllegalStateException
301         *             if this StopWatch has not been started
302         * @since 2.4
303         */
304        public long getStartTime() {
305            if (this.runningState == STATE_UNSTARTED) {
306                throw new IllegalStateException("Stopwatch has not been started");
307            }
308            return this.startTime;
309        }
310    
311        /**
312         * <p>
313         * Gets a summary of the time that the stopwatch recorded as a string.
314         * </p>
315         * 
316         * <p>
317         * The format used is ISO8601-like, <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.
318         * </p>
319         * 
320         * @return the time as a String
321         */
322        public String toString() {
323            return DurationFormatUtils.formatDurationHMS(getTime());
324        }
325    
326        /**
327         * <p>
328         * Gets a summary of the split time that the stopwatch recorded as a string.
329         * </p>
330         * 
331         * <p>
332         * The format used is ISO8601-like, <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.
333         * </p>
334         * 
335         * @return the split time as a String
336         * @since 2.1
337         */
338        public String toSplitString() {
339            return DurationFormatUtils.formatDurationHMS(getSplitTime());
340        }
341    
342    }