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