KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > datetime > JStopWatch


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.datetime;
4
5 import java.util.List JavaDoc;
6 import java.util.ArrayList JavaDoc;
7
8 /**
9  * Nice stopwatch that supports time spans, cumulative times and laps.
10  * Useful for all kind of profilings, time measurements etc.
11  */

12 public class JStopWatch {
13
14     /**
15      * Optional stopwatch name.
16      */

17     protected String JavaDoc name;
18     /**
19      * Last start time.
20      */

21     protected long startTime;
22     /**
23      * Last stop time.
24      */

25     protected long stopTime;
26     /**
27      * Last elapsed time.
28      */

29     protected long spanTime;
30     /**
31      * Cumulative elapsed time.
32      */

33     protected long totalTime;
34     /**
35      * Running flag.
36      */

37     protected boolean running;
38
39     // ---------------------------------------------------------------- ctors
40

41     /**
42      * Starts the stopwatch.
43      */

44     public JStopWatch() {
45         this("");
46     }
47
48     /**
49      * Starts the named stopwatch.
50      */

51     public JStopWatch(String JavaDoc name) {
52         this.name = name;
53         start();
54     }
55
56     /**
57      * Returns stopwatch name.
58      */

59     public String JavaDoc getName() {
60         return name;
61     }
62
63     /**
64      * Returns <code>true</code> if stopwatch is running.
65      */

66     public boolean isRunning() {
67         return running;
68     }
69
70     // ---------------------------------------------------------------- basic
71

72     /**
73      * Starts the stopwatch. {@link #stop()} must be called prior to restart.
74      * Returns starting time in milliseconds.
75      */

76     public long start() {
77         if (running == false) {
78             startTime = System.currentTimeMillis();
79             running = true;
80         }
81         return startTime;
82     }
83
84     /**
85      * Restarts the stopwatch.
86      */

87     public long restart() {
88         startTime = System.currentTimeMillis();
89         running = true;
90         return startTime;
91     }
92
93     /**
94      * Stops the stopwatch if running. Returns span time.
95      * If laps are used, marks the last lap.
96      */

97     public long stop() {
98         if (running == true) {
99             stopTime = System.currentTimeMillis();
100             if (laps != null) {
101                 lap(stopTime);
102             }
103             spanTime = stopTime - startTime;
104             totalTime += stopTime - startTime;
105             running = false;
106         }
107         return spanTime;
108     }
109     
110     /**
111      * Returns total elapsed time from the {@link #start()} in ms.
112      */

113     public long elapsed() {
114         return System.currentTimeMillis() - startTime;
115     }
116
117     /**
118      * Stops the stopwatch and returns total cumulative time in ms.
119      */

120     public long total() {
121         stop();
122         return totalTime;
123     }
124
125     /**
126      * Stops the stopwatch and returns total time span for last
127      * start-stop sequence.
128      */

129     public long span() {
130         stop();
131         return spanTime;
132     }
133
134
135     // ---------------------------------------------------------------- laps
136

137     /**
138      * List of all laps. Contains long arrays in following format:
139      * <ul>
140      * <li>lap time - current lap time,</li>
141      * <li>lap span time - elapsed time from start,</li>
142      * <li>lap millis - lap milliseconds.
143      * </ul>
144      */

145     protected List JavaDoc laps;
146
147     /**
148      * Marks a lap and returns its length. May be called only while stop watch is running.
149      */

150     public long lap() {
151         return lap(System.currentTimeMillis());
152     }
153
154     protected long lap(long lap) {
155         if (running == false) {
156             return 0;
157         }
158         long lapSpanTime = lap - startTime;
159         long lapTime;
160         if (laps == null) {
161             lapTime = lapSpanTime;
162             laps = new ArrayList JavaDoc();
163         } else {
164             long[] previous = (long[]) laps.get(laps.size() - 1);
165             lapTime = lap - previous[2];
166         }
167         laps.add(new long[] {lapTime, lapSpanTime, lap});
168         return lapTime;
169     }
170
171     /**
172      * Returns the total number of laps up to this moment.
173      */

174     public int totalLaps() {
175         if (laps == null) {
176             return 0;
177         }
178         return laps.size();
179     }
180
181     /**
182      * Returns lap times for 1-based lap index.
183      * Returns <code>null</code> if laps are not used or if index is invalid.
184      */

185     public long[] getLapTimes(int index) {
186         if (laps == null) {
187             return null;
188         }
189         if ((index <= 0) || (index > laps.size())) {
190             return null;
191         }
192         return (long[]) laps.get(index - 1);
193     }
194
195     // ---------------------------------------------------------------- output
196

197     /**
198      * Returns total elapsed time as formated string from the last start.
199      */

200     public String JavaDoc toString() {
201         long elapsed = elapsed();
202         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
203         sb.append("JStopWatch ").append(name).append(running ? " is running." : "").append('\n');
204         if (running == true) {
205             sb.append("elapsed: ").append(formatTimeSpan(elapsed));
206         } else {
207             if (spanTime != totalTime) {
208                 sb.append("span: ").append(formatTimeSpan(spanTime)).append('\n');
209             }
210             sb.append("total: ").append(formatTimeSpan(totalTime));
211         }
212         if (laps != null) {
213             if (laps.isEmpty() == false) {
214                 sb.append('\n');
215             }
216             for (int i = 0; i < laps.size(); i++) {
217                 long[] longs = (long[]) laps.get(i);
218                 sb.append(" lap #").append(i + 1).append(':').append('\t');
219                 sb.append(formatTimeSpan(longs[0])).append('\t');
220                 sb.append(formatTimeSpan(longs[1])).append('\n');
221             }
222         }
223         return sb.toString();
224     }
225
226     /**
227      * Formats time spans.
228      */

229     public static String JavaDoc formatTimeSpan(long millis) {
230         long seconds = 0;
231         long minutes = 0;
232         long hours = 0;
233
234         if (millis > 1000) {
235             seconds = millis / 1000;
236             millis %= 1000;
237         }
238         if (seconds > 60) {
239             minutes = seconds / 60;
240             seconds %= 60;
241         }
242         if (minutes > 60) {
243             hours = minutes / 60;
244             minutes %= 60;
245         }
246
247         StringBuffer JavaDoc result = new StringBuffer JavaDoc(20);
248         boolean out = false;
249         if (hours > 0) {
250             result.append(hours).append(':');
251             out = true;
252         }
253         if ((out == true) || (minutes > 0)) {
254             if (minutes < 10) {
255                 result.append('0');
256             }
257             result.append(minutes).append(':');
258         }
259
260         if (seconds < 10) {
261             result.append('0');
262         }
263         result.append(seconds).append('.');
264
265         if (millis < 10) {
266             result.append('0');
267         }
268         if (millis < 100) {
269             result.append('0');
270         }
271         result.append(millis);
272         return result.toString();
273     }
274 }
275
Popular Tags