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 public void start(String name) {
53 this.name = name;
54 startTime = System.nanoTime();
55 status = TimeInstrumentStatus.STARTED;
56 }
57
58 public String getName() {
59 return name;
60 }
61
62 public TimeInstrument stop() {
63 if (status == TimeInstrumentStatus.STOPPED) {
64 return this;
65 }
66 return stop(System.nanoTime());
67 }
68
69 public StopWatch stop(long stopTime) {
70 this.status = TimeInstrumentStatus.STOPPED;
71 this.stopTime = stopTime;
72 return this;
73 }
74
75 @Override
76 public String toString() {
77 StringBuilder buf = new StringBuilder();
78 buf.append("StopWatch [");
79 buf.append(name);
80 buf.append("] ");
81
82 switch (status) {
83 case STARTED:
84 buf.append("STARTED");
85 break;
86 case STOPPED:
87 buf.append("elapsed time: ");
88 buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND));
89 break;
90 default:
91 throw new IllegalStateException("Status " + status + " is not expected");
92 }
93 return buf.toString();
94 }
95
96 public final long elapsedTime() {
97 if (status == TimeInstrumentStatus.STARTED) {
98 return 0;
99 } else {
100 return stopTime - startTime;
101 }
102 }
103
104 public TimeInstrumentStatus getStatus() {
105 return status;
106 }
107
108 public void print() {
109 System.out.println(toString());
110 }
111
112 public void log() {
113 throw new UnsupportedOperationException("A stopwatch instance does not know how to log");
114 }
115
116 }