Stopwatch.java revision 7dd252788645e940eada959bdde927426e2531c9
1/* 2 * Copyright (C) 2008 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.common.base; 18 19import static com.google.common.base.Preconditions.checkNotNull; 20import static com.google.common.base.Preconditions.checkState; 21import static java.util.concurrent.TimeUnit.MICROSECONDS; 22import static java.util.concurrent.TimeUnit.MILLISECONDS; 23import static java.util.concurrent.TimeUnit.NANOSECONDS; 24import static java.util.concurrent.TimeUnit.SECONDS; 25 26import com.google.common.annotations.Beta; 27import com.google.common.annotations.GwtCompatible; 28import com.google.common.annotations.GwtIncompatible; 29 30import java.util.concurrent.TimeUnit; 31 32/** 33 * An object that measures elapsed time in nanoseconds. It is useful to measure 34 * elapsed time using this class instead of direct calls to {@link 35 * System#nanoTime} for a few reasons: 36 * 37 * <ul> 38 * <li>An alternate time source can be substituted, for testing or performance 39 * reasons. 40 * <li>As documented by {@code nanoTime}, the value returned has no absolute 41 * meaning, and can only be interpreted as relative to another timestamp 42 * returned by {@code nanoTime} at a different time. {@code Stopwatch} is a 43 * more effective abstraction because it exposes only these relative values, 44 * not the absolute ones. 45 * </ul> 46 * 47 * <p>Basic usage: 48 * <pre> 49 * Stopwatch stopwatch = new Stopwatch().{@link #start start}(); 50 * doSomething(); 51 * stopwatch.{@link #stop stop}(); // optional 52 * 53 * long millis = stopwatch.elapsed(MILLISECONDS); 54 * 55 * log.info("that took: " + stopwatch); // formatted string like "12.3 ms" 56 * </pre> 57 * 58 * <p>Stopwatch methods are not idempotent; it is an error to start or stop a 59 * stopwatch that is already in the desired state. 60 * 61 * <p>When testing code that uses this class, use the {@linkplain 62 * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker. 63 * <!-- TODO(kevinb): restore the "such as" --> This allows you to 64 * simulate any valid behavior of the stopwatch. 65 * 66 * <p><b>Note:</b> This class is not thread-safe. 67 * 68 * @author Kevin Bourrillion 69 * @since 10.0 70 */ 71@Beta 72@GwtCompatible(emulated = true) 73public final class Stopwatch { 74 private final Ticker ticker; 75 private boolean isRunning; 76 private long elapsedNanos; 77 private long startTick; 78 79 /** 80 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} 81 * as its time source. 82 */ 83 public Stopwatch() { 84 this(Ticker.systemTicker()); 85 } 86 87 /** 88 * Creates (but does not start) a new stopwatch, using the specified time 89 * source. 90 */ 91 public Stopwatch(Ticker ticker) { 92 this.ticker = checkNotNull(ticker, "ticker"); 93 } 94 95 /** 96 * Returns {@code true} if {@link #start()} has been called on this stopwatch, 97 * and {@link #stop()} has not been called since the last call to {@code 98 * start()}. 99 */ 100 public boolean isRunning() { 101 return isRunning; 102 } 103 104 /** 105 * Starts the stopwatch. 106 * 107 * @return this {@code Stopwatch} instance 108 * @throws IllegalStateException if the stopwatch is already running. 109 */ 110 public Stopwatch start() { 111 checkState(!isRunning, 112 "This stopwatch is already running; it cannot be started more than once."); 113 isRunning = true; 114 startTick = ticker.read(); 115 return this; 116 } 117 118 /** 119 * Stops the stopwatch. Future reads will return the fixed duration that had 120 * elapsed up to this point. 121 * 122 * @return this {@code Stopwatch} instance 123 * @throws IllegalStateException if the stopwatch is already stopped. 124 */ 125 public Stopwatch stop() { 126 long tick = ticker.read(); 127 checkState(isRunning, "This stopwatch is already stopped; it cannot be stopped more than once."); 128 isRunning = false; 129 elapsedNanos += tick - startTick; 130 return this; 131 } 132 133 /** 134 * Sets the elapsed time for this stopwatch to zero, 135 * and places it in a stopped state. 136 * 137 * @return this {@code Stopwatch} instance 138 */ 139 public Stopwatch reset() { 140 elapsedNanos = 0; 141 isRunning = false; 142 return this; 143 } 144 145 private long elapsedNanos() { 146 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 147 } 148 149 /** 150 * Returns the current elapsed time shown on this stopwatch, expressed 151 * in the desired time unit, with any fraction rounded down. 152 * 153 * <p>Note that the overhead of measurement can be more than a microsecond, so 154 * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} 155 * precision here. 156 * 157 * @since 14.0 (since 10.0 as {@code elapsedTime()}) 158 */ 159 public long elapsed(TimeUnit desiredUnit) { 160 return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 161 } 162 163 /** 164 * Returns the current elapsed time shown on this stopwatch, expressed 165 * in the desired time unit, with any fraction rounded down. 166 * 167 * <p>Note that the overhead of measurement can be more than a microsecond, so 168 * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} 169 * precision here. 170 * 171 * @deprecated Use {@link Stopwatch#elapsed(TimeUnit)} instead. This method is 172 * scheduled to be removed in Guava release 16.0. 173 */ 174 @Deprecated 175 public long elapsedTime(TimeUnit desiredUnit) { 176 return elapsed(desiredUnit); 177 } 178 179 /** 180 * Returns the current elapsed time shown on this stopwatch, expressed 181 * in milliseconds, with any fraction rounded down. This is identical to 182 * {@code elapsed(TimeUnit.MILLISECONDS)}. 183 * 184 * @deprecated Use {@code stopwatch.elapsed(MILLISECONDS)} instead. This 185 * method is scheduled to be removed in Guava release 16.0. 186 */ 187 @Deprecated 188 public long elapsedMillis() { 189 return elapsed(MILLISECONDS); 190 } 191 192 /** 193 * Returns a string representation of the current elapsed time. 194 */ 195 @Override 196 @GwtIncompatible("String.format()") 197 public String toString() { 198 return toString(4); 199 } 200 201 /** 202 * Returns a string representation of the current elapsed time, choosing an 203 * appropriate unit and using the specified number of significant figures. 204 * For example, at the instant when {@code elapsed(NANOSECONDS)} would 205 * return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}. 206 * 207 * @deprecated Use {@link #toString()} instead. This method is scheduled 208 * to be removed in Guava release 15.0. 209 */ 210 @Deprecated 211 @GwtIncompatible("String.format()") 212 public String toString(int significantDigits) { 213 long nanos = elapsedNanos(); 214 215 TimeUnit unit = chooseUnit(nanos); 216 double value = (double) nanos / NANOSECONDS.convert(1, unit); 217 218 // Too bad this functionality is not exposed as a regular method call 219 return String.format("%." + significantDigits + "g %s", value, abbreviate(unit)); 220 } 221 222 private static TimeUnit chooseUnit(long nanos) { 223 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 224 return SECONDS; 225 } 226 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 227 return MILLISECONDS; 228 } 229 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 230 return MICROSECONDS; 231 } 232 return NANOSECONDS; 233 } 234 235 private static String abbreviate(TimeUnit unit) { 236 switch (unit) { 237 case NANOSECONDS: 238 return "ns"; 239 case MICROSECONDS: 240 return "\u03bcs"; // μs 241 case MILLISECONDS: 242 return "ms"; 243 case SECONDS: 244 return "s"; 245 default: 246 throw new AssertionError(); 247 } 248 } 249} 250