1 package jimm.util; 2 import java.io.PrintWriter ; 3 4 18 public class StopWatch { 19 20 protected String name; 21 protected long t0; 22 protected long elapsedTime; 23 protected PrintWriter out; 24 25 public StopWatch() { 26 this(null, null); 27 } 28 29 public StopWatch(String name) { 30 this(name, null); 31 } 32 33 public StopWatch(PrintWriter out) { 34 this(null, out); 35 } 36 37 public StopWatch(String name, PrintWriter out) { 38 this.name = name; 39 if (out == null) 40 this.out = new PrintWriter (System.err); 41 else 42 this.out = out; 43 elapsedTime = -1L; } 45 46 49 public void start() { 50 start(true); 51 } 52 53 59 public void start(boolean printStarting) { 60 if (t0 != 0) 61 System.err.println("(warning: StopWatch already started; resetting)"); 62 if (printStarting && name != null) 63 System.err.println("starting " + name); 64 elapsedTime = 0; 65 t0 = System.currentTimeMillis(); 66 } 67 68 71 public void pause() { 72 long now = System.currentTimeMillis(); 73 elapsedTime += now - t0; 74 t0 = 0; 75 } 76 77 80 public void resume() { 81 t0 = System.currentTimeMillis(); 82 } 83 84 87 public void mark() { 88 stop(null, true); 89 } 90 91 98 public void mark(boolean printMark) { 99 stop(null, printMark); 100 } 101 102 108 public void mark(String msg) { 109 stop(msg, true); 110 } 111 112 121 public void mark(String msg, boolean printMark) { 122 stop(msg, printMark); 123 } 124 125 129 public void stop() { 130 stop(null, true); 131 } 132 133 139 public void stop(String msg) { 140 stop(msg, true); 141 } 142 143 152 public void stop(String msg, boolean printName) { 153 long now = System.currentTimeMillis(); 154 155 if (elapsedTime == -1) { 156 System.err.println("(StopWatch" 157 + (name != null ? (" \"" + name + '"') : "") 158 + " was stopped without ever being started)"); 159 return; 160 } 161 162 long total = elapsedTime; 163 if (t0 != 0) 164 total += now - t0; 165 166 String separator = null; 167 if (printName && name != null) { 168 System.err.print(name); 169 separator = ": "; 170 } 171 if (msg != null) { 172 if (separator != null) 173 System.err.print(' '); 174 System.err.print("(" + msg + ")"); 175 separator = ": "; 176 } 177 if (separator != null) 178 System.err.print(separator); 179 180 System.err.println("" + (total / 1000.0) + " seconds"); 181 } 182 183 } 184 | Popular Tags |