KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ElapsedTimer


1 /*
2  * ElapsedTimer.java
3  *
4  * The contents of this file are subject to the terms of the Common Development
5  * and Distribution License (the License). You may not use this file except in
6  * compliance with the License.
7  *
8  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
9  * or http://www.netbeans.org/cddl.txt.
10  *
11  * When distributing Covered Code, include this CDDL Header Notice in each file
12  * and include the License file at http://www.netbeans.org/cddl.txt.
13  * If applicable, add the following below the CDDL Header, with the fields
14  * enclosed by brackets [] replaced by your own identifying information:
15  * "Portions Copyrighted [year] [name of copyright owner]"
16  *
17  * The Original Software is NetBeans. The Initial Developer of the Original
18  * Software is Sun Microsystems, Inc. Portions Copyright 2000-2001 Sun
19  * Microsystems, Inc. All Rights Reserved.
20  *
21  * Contributor(s): Thomas Ball
22  *
23  * Version: $Revision: 1.2 $
24  */

25
26 /**
27  * A simple class for calculating and reporting elapsed system time.
28  * Each timer has a start time and may have an end time. If an
29  * elapsed time value is requested of a timer which doesn't have its
30  * stop time set, the current system time is used.
31  *
32  * @author Tom Ball
33  */

34 public class ElapsedTimer {
35     // System times in milliseconds; see System.currentTimeMillis();
36
private long startTime;
37     private long stopTime;
38
39     /**
40      * Create a new timer.
41      */

42     public ElapsedTimer() {
43     reset();
44     }
45
46     /**
47      * Stop the current timer; that is, set its stopTime.
48      */

49     public void stop() {
50     stopTime = System.currentTimeMillis();
51     }
52
53     /**
54      * Reset the starting time to the current system time.
55      */

56     public final void reset() {
57     startTime = System.currentTimeMillis();
58     }
59
60     public long getElapsedMilliseconds() {
61     long st = (stopTime == 0) ? System.currentTimeMillis() : stopTime;
62     return st - startTime;
63     }
64
65     public int getElapsedSeconds() {
66     return (int)(getElapsedMilliseconds() / 1000L);
67     }
68
69     public String JavaDoc toString() {
70     long ms = getElapsedMilliseconds();
71     int sec = (int)(ms / 1000L);
72     int frac = (int)(ms % 1000L);
73     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
74     sb.append(ms / 1000L);
75     sb.append('.');
76     sb.append(ms % 1000L);
77     sb.append(" seconds");
78     return sb.toString();
79     }
80 }
81
Popular Tags