1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.slf4j.profiler;
26
27
28
29
30
31
32
33
34 public class StopWatch implements TimeInstrument {
35
36 private String name;
37 private long startTime;
38 private long stopTime;
39 TimeInstrumentStatus status;
40
41 public StopWatch(String name) {
42 start(name);
43 }
44
45 StopWatch(StopWatch original) {
46 this.name = original.name;
47 this.startTime = original.startTime;
48 this.stopTime = original.stopTime;
49 this.status = original.status;
50 }
51
52
53 public void start(String name) {
54 this.name = name;
55 startTime = System.nanoTime();
56 status = TimeInstrumentStatus.STARTED;
57 }
58
59 public String getName() {
60 return name;
61 }
62
63 public TimeInstrument stop() {
64 if(status == TimeInstrumentStatus.STOPPED) {
65 return this;
66 }
67 return stop(System.nanoTime());
68 }
69
70 public StopWatch stop(long stopTime) {
71 this.status = TimeInstrumentStatus.STOPPED;
72 this.stopTime = stopTime;
73 return this;
74 }
75
76 @Override
77 public String toString() {
78 StringBuffer buf = new StringBuffer();
79 buf.append("StopWatch [");
80 buf.append(name);
81 buf.append("] ");
82
83 switch (status) {
84 case STARTED:
85 buf.append("STARTED");
86 break;
87 case STOPPED:
88 buf.append("elapsed time: ");
89 buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND));
90 break;
91 default:
92 throw new IllegalStateException("Status " + status + " is not expected");
93 }
94 return buf.toString();
95 }
96
97 public final long elapsedTime() {
98 if (status == TimeInstrumentStatus.STARTED) {
99 return 0;
100 } else {
101 return stopTime - startTime;
102 }
103 }
104
105 public TimeInstrumentStatus getStatus() {
106 return status;
107 }
108
109 public void print() {
110 System.out.println(toString());
111 }
112
113 public void log() {
114 throw new UnsupportedOperationException("A stopwatch instance does not know how to log");
115 }
116
117 }