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(); // requires API Level 17 083 * } 084 * }); 085 * }</pre> 086 * 087 * @author Kevin Bourrillion 088 * @since 10.0 089 */ 090@GwtCompatible(emulated = true) 091@SuppressWarnings("GoodTime") // lots of violations 092@ElementTypesAreNonnullByDefault 093public final class Stopwatch { 094 private final Ticker ticker; 095 private boolean isRunning; 096 private long elapsedNanos; 097 private long startTick; 098 099 /** 100 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 101 * 102 * @since 15.0 103 */ 104 public static Stopwatch createUnstarted() { 105 return new Stopwatch(); 106 } 107 108 /** 109 * Creates (but does not start) a new stopwatch, using the specified time source. 110 * 111 * @since 15.0 112 */ 113 public static Stopwatch createUnstarted(Ticker ticker) { 114 return new Stopwatch(ticker); 115 } 116 117 /** 118 * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 119 * 120 * @since 15.0 121 */ 122 public static Stopwatch createStarted() { 123 return new Stopwatch().start(); 124 } 125 126 /** 127 * Creates (and starts) a new stopwatch, using the specified time source. 128 * 129 * @since 15.0 130 */ 131 public static Stopwatch createStarted(Ticker ticker) { 132 return new Stopwatch(ticker).start(); 133 } 134 135 Stopwatch() { 136 this.ticker = Ticker.systemTicker(); 137 } 138 139 Stopwatch(Ticker ticker) { 140 this.ticker = checkNotNull(ticker, "ticker"); 141 } 142 143 /** 144 * Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()} 145 * has not been called since the last call to {@code start()}. 146 */ 147 public boolean isRunning() { 148 return isRunning; 149 } 150 151 /** 152 * Starts the stopwatch. 153 * 154 * @return this {@code Stopwatch} instance 155 * @throws IllegalStateException if the stopwatch is already running. 156 */ 157 @CanIgnoreReturnValue 158 public Stopwatch start() { 159 checkState(!isRunning, "This stopwatch is already running."); 160 isRunning = true; 161 startTick = ticker.read(); 162 return this; 163 } 164 165 /** 166 * Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this 167 * point. 168 * 169 * @return this {@code Stopwatch} instance 170 * @throws IllegalStateException if the stopwatch is already stopped. 171 */ 172 @CanIgnoreReturnValue 173 public Stopwatch stop() { 174 long tick = ticker.read(); 175 checkState(isRunning, "This stopwatch is already stopped."); 176 isRunning = false; 177 elapsedNanos += tick - startTick; 178 return this; 179 } 180 181 /** 182 * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 183 * 184 * @return this {@code Stopwatch} instance 185 */ 186 @CanIgnoreReturnValue 187 public Stopwatch reset() { 188 elapsedNanos = 0; 189 isRunning = false; 190 return this; 191 } 192 193 private long elapsedNanos() { 194 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 195 } 196 197 /** 198 * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 199 * with any fraction rounded down. 200 * 201 * <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally 202 * not useful to specify {@link TimeUnit#NANOSECONDS} precision here. 203 * 204 * <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent 205 * elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a 206 * strongly-typed {@code Duration} instance. 207 * 208 * @since 14.0 (since 10.0 as {@code elapsedTime()}) 209 */ 210 public long elapsed(TimeUnit desiredUnit) { 211 return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 212 } 213 214 /** 215 * Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link 216 * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 217 * 218 * @since 22.0 219 */ 220 @GwtIncompatible 221 @J2ObjCIncompatible 222 public Duration elapsed() { 223 return Duration.ofNanos(elapsedNanos()); 224 } 225 226 /** Returns a string representation of the current elapsed time. */ 227 @Override 228 public String toString() { 229 long nanos = elapsedNanos(); 230 231 TimeUnit unit = chooseUnit(nanos); 232 double value = (double) nanos / NANOSECONDS.convert(1, unit); 233 234 // Too bad this functionality is not exposed as a regular method call 235 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 236 } 237 238 private static TimeUnit chooseUnit(long nanos) { 239 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 240 return DAYS; 241 } 242 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 243 return HOURS; 244 } 245 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 246 return MINUTES; 247 } 248 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 249 return SECONDS; 250 } 251 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 252 return MILLISECONDS; 253 } 254 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 255 return MICROSECONDS; 256 } 257 return NANOSECONDS; 258 } 259 260 private static String abbreviate(TimeUnit unit) { 261 switch (unit) { 262 case NANOSECONDS: 263 return "ns"; 264 case MICROSECONDS: 265 return "\u03bcs"; // μs 266 case MILLISECONDS: 267 return "ms"; 268 case SECONDS: 269 return "s"; 270 case MINUTES: 271 return "min"; 272 case HOURS: 273 return "h"; 274 case DAYS: 275 return "d"; 276 default: 277 throw new AssertionError(); 278 } 279 } 280}