1 14 package org.wings.util; 15 16 import java.text.MessageFormat ; 17 import java.util.ArrayList ; 18 import java.util.Iterator ; 19 20 29 30 38 public class TimeMeasure { 39 protected final static double RESOLUTION = 100.0; 40 41 44 protected final ArrayList measures; 45 46 49 protected final MessageFormat formatter; 50 51 54 protected Measure current; 55 56 59 public TimeMeasure() { 60 this(new MessageFormat ("{0}\t: {1}\t {2}x\n")); 61 } 62 63 73 public TimeMeasure(MessageFormat formatter) { 74 this.measures = new ArrayList (); 75 this.formatter = formatter; 76 } 77 78 81 public void reset() { 82 measures.clear(); 83 } 84 85 89 public void start(String comment) { 90 current = new Measure(comment); 91 } 92 93 103 104 121 122 125 public void stop() { 126 if (current != null) { 127 current.stop(); 128 measures.add(current); 129 current = null; 130 } 131 } 132 133 140 private long findReferenceValue(boolean findShortest) { 141 long result = findShortest ? Long.MAX_VALUE : -1; 142 143 Iterator it = measures.iterator(); 144 while (it.hasNext()) { 145 Measure m = (Measure) it.next(); 146 result = (findShortest 147 ? Math.min(result, m.getDuration()) 148 : Math.max(result, m.getDuration())); 149 } 150 return result; 151 } 152 153 public String print() { 154 return print(false); 155 } 156 157 168 public String print(boolean shortestIsReference) { 169 StringBuffer result = new StringBuffer (); 170 long reference = findReferenceValue(shortestIsReference); 171 Iterator it = measures.iterator(); 172 while (it.hasNext()) { 173 Measure m = (Measure) it.next(); 174 String factor = " -- "; 175 long duration = m.getDuration(); 176 if (reference > 0) { 177 long tmp = (long) ((duration * RESOLUTION) / reference); 178 factor = String.valueOf(tmp / RESOLUTION); 179 } 180 Object [] args = {m.getComment(), (duration + "ms"), factor}; 181 result.append(formatter.format(args)); 182 } 183 return result.toString(); 184 } 185 186 public String toString() { 187 return print(); 188 } 189 190 193 private final static class Measure { 194 197 private final long start; 198 199 202 private long stop; 203 204 207 private long duration; 208 209 212 private String comment; 213 214 public Measure(String comment) { 215 start = System.currentTimeMillis(); 216 this.comment = comment; 217 } 218 219 public void stop() { 220 stop = System.currentTimeMillis(); 221 duration = stop - start; 222 } 223 224 public long getDuration() { return duration; } 225 226 public String getComment() { return comment; } 227 } 228 } 229 230 231 | Popular Tags |