KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > datetime > SimpleTimer


1 package jodd.datetime;
2
3 /**
4  * Measures time periods.
5  */

6 public class SimpleTimer {
7     
8     private long startTime;
9     private long stopTime = 0;
10
11
12     /**
13      * Initialization and timer begins to count.
14      */

15     public SimpleTimer() {
16         stopTime = 0;
17         start();
18     }
19
20     /**
21      * Starts the timer. If timer was already running, it resets.
22      */

23     public void start() {
24         startTime = System.currentTimeMillis();
25     }
26
27     /**
28      * Stops timer and returns elapsed time from last timer start in ms.
29      *
30      * @return elapsed time in ms
31      */

32     public long stop() {
33         stopTime = System.currentTimeMillis();
34         return stopTime - startTime;
35     }
36
37     /**
38      * Returns elapsed time from the last start and keeps timer running.
39      *
40      * @return elapsed time in ms
41      */

42     public long lap() {
43         return System.currentTimeMillis() - startTime;
44     }
45
46     /**
47      * Stops timer if running. Returns elapsed time from the last timer start.
48      * If timer is not running, returns last measured time.
49      *
50      * @return elapsed time in ms
51      */

52     public long elapsed() {
53         if (stopTime < startTime) {
54             stopTime = System.currentTimeMillis();
55         }
56         return stopTime - startTime;
57     }
58
59     
60     /**
61      * Returns elapsed time as String from the last start.
62      *
63      * @return elapsed time in ms
64      */

65     public String toString() {
66         return (new Long(stopTime - startTime)).toString();
67     }
68 }
69
Popular Tags