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 Stopwatch() { 135 this.ticker = Ticker.systemTicker(); 136 } 137 138 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 as a {@link Duration}. Unlike {@link 215 * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 216 * 217 * @since 22.0 218 */ 219 @GwtIncompatible 220 @J2ObjCIncompatible 221 public Duration elapsed() { 222 return Duration.ofNanos(elapsedNanos()); 223 } 224 225 /** Returns a string representation of the current elapsed time. */ 226 @Override 227 public String toString() { 228 long nanos = elapsedNanos(); 229 230 TimeUnit unit = chooseUnit(nanos); 231 double value = (double) nanos / NANOSECONDS.convert(1, unit); 232 233 // Too bad this functionality is not exposed as a regular method call 234 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 235 } 236 237 private static TimeUnit chooseUnit(long nanos) { 238 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 239 return DAYS; 240 } 241 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 242 return HOURS; 243 } 244 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 245 return MINUTES; 246 } 247 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 248 return SECONDS; 249 } 250 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 251 return MILLISECONDS; 252 } 253 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 254 return MICROSECONDS; 255 } 256 return NANOSECONDS; 257 } 258 259 private static String abbreviate(TimeUnit unit) { 260 switch (unit) { 261 case NANOSECONDS: 262 return "ns"; 263 case MICROSECONDS: 264 return "\u03bcs"; // μs 265 case MILLISECONDS: 266 return "ms"; 267 case SECONDS: 268 return "s"; 269 case MINUTES: 270 return "min"; 271 case HOURS: 272 return "h"; 273 case DAYS: 274 return "d"; 275 default: 276 throw new AssertionError(); 277 } 278 } 279}