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.common.annotations.J2ktIncompatible; 030import com.google.errorprone.annotations.CanIgnoreReturnValue; 031import com.google.j2objc.annotations.J2ObjCIncompatible; 032import java.time.Duration; 033import java.util.concurrent.TimeUnit; 034 035/** 036 * An object that accurately measures <i>elapsed time</i>: the measured duration between two 037 * successive readings of "now" in the same process. 038 * 039 * <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like 040 * {@link System#currentTimeMillis()}, best represented as an {@link java.time.Instant}. Such values 041 * <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but 042 * doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings 043 * are inherently approximate, routinely affected by periodic clock corrections. Because this class 044 * (by default) uses {@link System#nanoTime}, it is unaffected by these changes. 045 * 046 * <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons: 047 * 048 * <ul> 049 * <li>The raw {@code long} values returned by {@code nanoTime} are meaningless and unsafe to use 050 * in any other way than how {@code Stopwatch} uses them. 051 * <li>An alternative source of nanosecond ticks can be substituted, for example for testing or 052 * performance reasons, without affecting most of your code. 053 * </ul> 054 * 055 * <p>The one downside of {@code Stopwatch} relative to {@link System#nanoTime()} is that {@code 056 * Stopwatch} requires object allocation and additional method calls, which can reduce the accuracy 057 * of the elapsed times reported. {@code Stopwatch} is still suitable for logging and metrics where 058 * reasonably accurate values are sufficient. If the uncommon case that you need to maximize 059 * accuracy, use {@code System.nanoTime()} directly instead. 060 * 061 * <p>Basic usage: 062 * 063 * <pre>{@code 064 * Stopwatch stopwatch = Stopwatch.createStarted(); 065 * doSomething(); 066 * stopwatch.stop(); // optional 067 * 068 * Duration duration = stopwatch.elapsed(); 069 * 070 * log.info("time: " + stopwatch); // formatted string like "12.3 ms" 071 * }</pre> 072 * 073 * <p>The state-changing methods are not idempotent; it is an error to start or stop a stopwatch 074 * that is already in the desired state. 075 * 076 * <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link 077 * #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid 078 * behavior of the stopwatch. 079 * 080 * <p><b>Note:</b> This class is not thread-safe. 081 * 082 * <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep 083 * time while the device is asleep. Instead, create one like this: 084 * 085 * <pre>{@code 086 * Stopwatch.createStarted( 087 * new Ticker() { 088 * public long read() { 089 * return android.os.SystemClock.elapsedRealtimeNanos(); // requires API Level 17 090 * } 091 * }); 092 * }</pre> 093 * 094 * @author Kevin Bourrillion 095 * @since 10.0 096 */ 097@GwtCompatible(emulated = true) 098@SuppressWarnings("GoodTime") // lots of violations 099@ElementTypesAreNonnullByDefault 100public final class Stopwatch { 101 private final Ticker ticker; 102 private boolean isRunning; 103 private long elapsedNanos; 104 private long startTick; 105 106 /** 107 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 108 * 109 * @since 15.0 110 */ 111 public static Stopwatch createUnstarted() { 112 return new Stopwatch(); 113 } 114 115 /** 116 * Creates (but does not start) a new stopwatch, using the specified time source. 117 * 118 * @since 15.0 119 */ 120 public static Stopwatch createUnstarted(Ticker ticker) { 121 return new Stopwatch(ticker); 122 } 123 124 /** 125 * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 126 * 127 * @since 15.0 128 */ 129 public static Stopwatch createStarted() { 130 return new Stopwatch().start(); 131 } 132 133 /** 134 * Creates (and starts) a new stopwatch, using the specified time source. 135 * 136 * @since 15.0 137 */ 138 public static Stopwatch createStarted(Ticker ticker) { 139 return new Stopwatch(ticker).start(); 140 } 141 142 Stopwatch() { 143 this.ticker = Ticker.systemTicker(); 144 } 145 146 Stopwatch(Ticker ticker) { 147 this.ticker = checkNotNull(ticker, "ticker"); 148 } 149 150 /** 151 * Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()} 152 * has not been called since the last call to {@code start()}. 153 */ 154 public boolean isRunning() { 155 return isRunning; 156 } 157 158 /** 159 * Starts the stopwatch. 160 * 161 * @return this {@code Stopwatch} instance 162 * @throws IllegalStateException if the stopwatch is already running. 163 */ 164 @CanIgnoreReturnValue 165 public Stopwatch start() { 166 checkState(!isRunning, "This stopwatch is already running."); 167 isRunning = true; 168 startTick = ticker.read(); 169 return this; 170 } 171 172 /** 173 * Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this 174 * point. 175 * 176 * @return this {@code Stopwatch} instance 177 * @throws IllegalStateException if the stopwatch is already stopped. 178 */ 179 @CanIgnoreReturnValue 180 public Stopwatch stop() { 181 long tick = ticker.read(); 182 checkState(isRunning, "This stopwatch is already stopped."); 183 isRunning = false; 184 elapsedNanos += tick - startTick; 185 return this; 186 } 187 188 /** 189 * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 190 * 191 * @return this {@code Stopwatch} instance 192 */ 193 @CanIgnoreReturnValue 194 public Stopwatch reset() { 195 elapsedNanos = 0; 196 isRunning = false; 197 return this; 198 } 199 200 private long elapsedNanos() { 201 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 202 } 203 204 /** 205 * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 206 * with any fraction rounded down. 207 * 208 * <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally 209 * not useful to specify {@link TimeUnit#NANOSECONDS} precision here. 210 * 211 * <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent 212 * elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a 213 * strongly-typed {@code Duration} instance. 214 * 215 * @since 14.0 (since 10.0 as {@code elapsedTime()}) 216 */ 217 public long elapsed(TimeUnit desiredUnit) { 218 return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 219 } 220 221 /** 222 * Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link 223 * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 224 * 225 * @since 22.0 226 */ 227 @J2ktIncompatible 228 @GwtIncompatible 229 @J2ObjCIncompatible 230 public Duration elapsed() { 231 return Duration.ofNanos(elapsedNanos()); 232 } 233 234 /** Returns a string representation of the current elapsed time. */ 235 @Override 236 public String toString() { 237 long nanos = elapsedNanos(); 238 239 TimeUnit unit = chooseUnit(nanos); 240 double value = (double) nanos / NANOSECONDS.convert(1, unit); 241 242 // Too bad this functionality is not exposed as a regular method call 243 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 244 } 245 246 private static TimeUnit chooseUnit(long nanos) { 247 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 248 return DAYS; 249 } 250 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 251 return HOURS; 252 } 253 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 254 return MINUTES; 255 } 256 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 257 return SECONDS; 258 } 259 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 260 return MILLISECONDS; 261 } 262 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 263 return MICROSECONDS; 264 } 265 return NANOSECONDS; 266 } 267 268 private static String abbreviate(TimeUnit unit) { 269 switch (unit) { 270 case NANOSECONDS: 271 return "ns"; 272 case MICROSECONDS: 273 return "\u03bcs"; // μs 274 case MILLISECONDS: 275 return "ms"; 276 case SECONDS: 277 return "s"; 278 case MINUTES: 279 return "min"; 280 case HOURS: 281 return "h"; 282 case DAYS: 283 return "d"; 284 default: 285 throw new AssertionError(); 286 } 287 } 288}