001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.base.Preconditions.checkState; 019import static java.util.concurrent.TimeUnit.DAYS; 020import static java.util.concurrent.TimeUnit.HOURS; 021import static java.util.concurrent.TimeUnit.MICROSECONDS; 022import static java.util.concurrent.TimeUnit.MILLISECONDS; 023import static java.util.concurrent.TimeUnit.MINUTES; 024import static java.util.concurrent.TimeUnit.NANOSECONDS; 025import static java.util.concurrent.TimeUnit.SECONDS; 026 027import com.google.common.annotations.GwtCompatible; 028import com.google.common.annotations.GwtIncompatible; 029import com.google.errorprone.annotations.CanIgnoreReturnValue; 030import com.google.j2objc.annotations.J2ObjCIncompatible; 031import java.time.Duration; 032import java.util.concurrent.TimeUnit; 033 034/** 035 * An object that accurately measures <i>elapsed time</i>: the measured duration between two 036 * successive readings of "now" in the same process. 037 * 038 * <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like 039 * {@link System#currentTimeMillis()}, best represented as an {@link Instant}. Such values 040 * <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but 041 * doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings 042 * are inherently approximate, routinely affected by periodic clock corrections. Because this class 043 * (by default) uses {@link System#nanoTime}, it is unaffected by these changes. 044 * 045 * <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons: 046 * 047 * <ul> 048 * <li>The raw {@code long} values returned by {@code nanoTime} are meaningless and unsafe to use 049 * in any other way than how {@code Stopwatch} uses them. 050 * <li>An alternative source of nanosecond ticks can be substituted, for example for testing or 051 * performance reasons, without affecting most of your code. 052 * </ul> 053 * 054 * <p>Basic usage: 055 * 056 * <pre>{@code 057 * Stopwatch stopwatch = Stopwatch.createStarted(); 058 * doSomething(); 059 * stopwatch.stop(); // optional 060 * 061 * Duration duration = stopwatch.elapsed(); 062 * 063 * log.info("time: " + stopwatch); // formatted string like "12.3 ms" 064 * }</pre> 065 * 066 * <p>The state-changing methods are not idempotent; it is an error to start or stop a stopwatch 067 * that is already in the desired state. 068 * 069 * <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link 070 * #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid 071 * behavior of the stopwatch. 072 * 073 * <p><b>Note:</b> This class is not thread-safe. 074 * 075 * <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep 076 * time while the device is asleep. Instead, create one like this: 077 * 078 * <pre>{@code 079 * Stopwatch.createStarted( 080 * new Ticker() { 081 * public long read() { 082 * return android.os.SystemClock.elapsedRealtimeNanos(); 083 * } 084 * }); 085 * }</pre> 086 * 087 * @author Kevin Bourrillion 088 * @since 10.0 089 */ 090@GwtCompatible(emulated = true) 091@SuppressWarnings("GoodTime") // lots of violations 092public final class Stopwatch { 093 private final Ticker ticker; 094 private boolean isRunning; 095 private long elapsedNanos; 096 private long startTick; 097 098 /** 099 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 100 * 101 * @since 15.0 102 */ 103 public static Stopwatch createUnstarted() { 104 return new Stopwatch(); 105 } 106 107 /** 108 * Creates (but does not start) a new stopwatch, using the specified time source. 109 * 110 * @since 15.0 111 */ 112 public static Stopwatch createUnstarted(Ticker ticker) { 113 return new Stopwatch(ticker); 114 } 115 116 /** 117 * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 118 * 119 * @since 15.0 120 */ 121 public static Stopwatch createStarted() { 122 return new Stopwatch().start(); 123 } 124 125 /** 126 * Creates (and starts) a new stopwatch, using the specified time source. 127 * 128 * @since 15.0 129 */ 130 public static Stopwatch createStarted(Ticker ticker) { 131 return new Stopwatch(ticker).start(); 132 } 133 134 public Stopwatch() { 135 this.ticker = Ticker.systemTicker(); 136 } 137 138 public Stopwatch(Ticker ticker) { 139 this.ticker = checkNotNull(ticker, "ticker"); 140 } 141 142 /** 143 * Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()} 144 * has not been called since the last call to {@code start()}. 145 */ 146 public boolean isRunning() { 147 return isRunning; 148 } 149 150 /** 151 * Starts the stopwatch. 152 * 153 * @return this {@code Stopwatch} instance 154 * @throws IllegalStateException if the stopwatch is already running. 155 */ 156 @CanIgnoreReturnValue 157 public Stopwatch start() { 158 checkState(!isRunning, "This stopwatch is already running."); 159 isRunning = true; 160 startTick = ticker.read(); 161 return this; 162 } 163 164 /** 165 * Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this 166 * point. 167 * 168 * @return this {@code Stopwatch} instance 169 * @throws IllegalStateException if the stopwatch is already stopped. 170 */ 171 @CanIgnoreReturnValue 172 public Stopwatch stop() { 173 long tick = ticker.read(); 174 checkState(isRunning, "This stopwatch is already stopped."); 175 isRunning = false; 176 elapsedNanos += tick - startTick; 177 return this; 178 } 179 180 /** 181 * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 182 * 183 * @return this {@code Stopwatch} instance 184 */ 185 @CanIgnoreReturnValue 186 public Stopwatch reset() { 187 elapsedNanos = 0; 188 isRunning = false; 189 return this; 190 } 191 192 private long elapsedNanos() { 193 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 194 } 195 196 /** 197 * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 198 * with any fraction rounded down. 199 * 200 * <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally 201 * not useful to specify {@link TimeUnit#NANOSECONDS} precision here. 202 * 203 * <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent 204 * elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a 205 * strongly-typed {@code Duration} instance. 206 * 207 * @since 14.0 (since 10.0 as {@code elapsedTime()}) 208 */ 209 public long elapsed(TimeUnit desiredUnit) { 210 return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 211 } 212 213 /** 214 * Returns the current elapsed time shown on this stopwatch, expressed 215 * in the desired time unit, with any fraction rounded down. 216 * 217 * <p>Note that the overhead of measurement can be more than a microsecond, so 218 * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} 219 * precision here. 220 * 221 * @deprecated Use {@link Stopwatch#elapsed(TimeUnit)} instead. This method is 222 * scheduled to be removed in Guava release 16.0. 223 */ 224 @Deprecated 225 public long elapsedTime(TimeUnit desiredUnit) { 226 return elapsed(desiredUnit); 227 } 228 229 /** 230 * Returns the current elapsed time shown on this stopwatch, expressed 231 * in milliseconds, with any fraction rounded down. This is identical to 232 * {@code elapsed(TimeUnit.MILLISECONDS)}. 233 * 234 * @deprecated Use {@code stopwatch.elapsed(MILLISECONDS)} instead. This 235 * method is scheduled to be removed in Guava release 16.0. 236 */ 237 @Deprecated 238 public long elapsedMillis() { 239 return elapsed(MILLISECONDS); 240 } 241 242 /** 243 * Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link 244 * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 245 * 246 * @since 22.0 247 */ 248 @GwtIncompatible 249 @J2ObjCIncompatible 250 public Duration elapsed() { 251 return Duration.ofNanos(elapsedNanos()); 252 } 253 254 /** Returns a string representation of the current elapsed time. */ 255 @Override 256 public String toString() { 257 long nanos = elapsedNanos(); 258 259 TimeUnit unit = chooseUnit(nanos); 260 double value = (double) nanos / NANOSECONDS.convert(1, unit); 261 262 // Too bad this functionality is not exposed as a regular method call 263 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 264 } 265 266 /** 267 * Returns a string representation of the current elapsed time, choosing an 268 * appropriate unit and using the specified number of significant figures. 269 * For example, at the instant when {@code elapsed(NANOSECONDS)} would 270 * return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}. 271 * 272 * @deprecated Use {@link #toString()} instead. This method is scheduled 273 * to be removed in Guava release 15.0. 274 */ 275 @Deprecated 276 public String toString(int significantDigits) { 277 long nanos = elapsedNanos(); 278 279 TimeUnit unit = chooseUnit(nanos); 280 double value = (double) nanos / NANOSECONDS.convert(1, unit); 281 282 // Too bad this functionality is not exposed as a regular method call 283 return String.format("%." + significantDigits + "g %s", 284 value, abbreviate(unit)); 285 } 286 287 private static TimeUnit chooseUnit(long nanos) { 288 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 289 return DAYS; 290 } 291 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 292 return HOURS; 293 } 294 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 295 return MINUTES; 296 } 297 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 298 return SECONDS; 299 } 300 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 301 return MILLISECONDS; 302 } 303 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 304 return MICROSECONDS; 305 } 306 return NANOSECONDS; 307 } 308 309 private static String abbreviate(TimeUnit unit) { 310 switch (unit) { 311 case NANOSECONDS: 312 return "ns"; 313 case MICROSECONDS: 314 return "\u03bcs"; // μs 315 case MILLISECONDS: 316 return "ms"; 317 case SECONDS: 318 return "s"; 319 case MINUTES: 320 return "min"; 321 case HOURS: 322 return "h"; 323 case DAYS: 324 return "d"; 325 default: 326 throw new AssertionError(); 327 } 328 } 329}