KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > spoon > support > util > Timer


1 package spoon.support.util;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.List JavaDoc;
5 import java.util.Stack JavaDoc;
6
7 /**
8  * A utility class for performance statistics of Spoon.
9  *
10  * @author Renaud Pawlak
11  */

12 public class Timer {
13     private static List JavaDoc<Timer> timestamps = new ArrayList JavaDoc<Timer>();
14
15     private static Stack JavaDoc<Timer> current = new Stack JavaDoc<Timer>();
16
17     /**
18      * Starts a timer.
19      *
20      * @param name
21      * the timer name
22      */

23     public static void start(String JavaDoc name) {
24         current.push(new Timer(name));
25     }
26
27     /**
28      * Stops a timer.
29      *
30      * @param name
31      * the timer name
32      */

33     public static void stop(String JavaDoc name) {
34         if (!current.peek().getName().equals(name)) {
35             throw new RuntimeException JavaDoc("Must stop last timer");
36         }
37         current.peek().stop();
38         timestamps.add(current.pop());
39     }
40
41     /**
42      * Displays all the timers.
43      */

44     public static void display() {
45         for (Timer time : timestamps) {
46             System.out.println(time);
47         }
48     }
49
50     String JavaDoc name;
51
52     long start, stop;
53
54     /**
55      * Constructs a timer.
56      *
57      * @param name
58      * the timer name
59      */

60     public Timer(String JavaDoc name) {
61         super();
62         this.name = name;
63         start = System.currentTimeMillis();
64     }
65
66     /**
67      * Stops the current timer.
68      */

69     public void stop() {
70         stop = System.currentTimeMillis();
71     }
72
73     /**
74      * Gets this timer's name.
75      *
76      * @return
77      */

78     public String JavaDoc getName() {
79         return name;
80     }
81
82     /**
83      * Gets the current time of this timer.
84      */

85     public long getValue() {
86         return stop - start;
87     }
88
89     /**
90      * A string representation of this timer.
91      */

92     @Override JavaDoc
93     public String JavaDoc toString() {
94         return getName() + " \t" + getValue() + "ms";
95     }
96
97 }
98
Popular Tags