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 measures elapsed time in nanoseconds. It is useful to measure elapsed time using 036 * this class instead of direct calls to {@link System#nanoTime} for a few reasons: 037 * 038 * <ul> 039 * <li>An alternate time source can be substituted, for testing or performance reasons. 040 * <li>As documented by {@code nanoTime}, the value returned has no absolute meaning, and can only 041 * be interpreted as relative to another timestamp returned by {@code nanoTime} at a different 042 * time. {@code Stopwatch} is a more effective abstraction because it exposes only these 043 * relative values, not the absolute ones. 044 * </ul> 045 * 046 * <p>Basic usage: 047 * 048 * <pre>{@code 049 * Stopwatch stopwatch = Stopwatch.createStarted(); 050 * doSomething(); 051 * stopwatch.stop(); // optional 052 * 053 * Duration duration = stopwatch.elapsed(); 054 * 055 * log.info("time: " + stopwatch); // formatted string like "12.3 ms" 056 * }</pre> 057 * 058 * <p>Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is 059 * already in the desired state. 060 * 061 * <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link 062 * #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid 063 * behavior of the stopwatch. 064 * 065 * <p><b>Note:</b> This class is not thread-safe. 066 * 067 * <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep 068 * time while the device is asleep. Instead, create one like this: 069 * 070 * <pre>{@code 071 * Stopwatch.createStarted( 072 * new Ticker() { 073 * public long read() { 074 * return android.os.SystemClock.elapsedRealtimeNanos(); 075 * } 076 * }); 077 * }</pre> 078 * 079 * @author Kevin Bourrillion 080 * @since 10.0 081 */ 082@GwtCompatible(emulated = true) 083@SuppressWarnings("GoodTime") // lots of violations 084public final class Stopwatch { 085 private final Ticker ticker; 086 private boolean isRunning; 087 private long elapsedNanos; 088 private long startTick; 089 090 /** 091 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 092 * 093 * @since 15.0 094 */ 095 public static Stopwatch createUnstarted() { 096 return new Stopwatch(); 097 } 098 099 /** 100 * Creates (but does not start) a new stopwatch, using the specified time source. 101 * 102 * @since 15.0 103 */ 104 public static Stopwatch createUnstarted(Ticker ticker) { 105 return new Stopwatch(ticker); 106 } 107 108 /** 109 * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 110 * 111 * @since 15.0 112 */ 113 public static Stopwatch createStarted() { 114 return new Stopwatch().start(); 115 } 116 117 /** 118 * Creates (and starts) a new stopwatch, using the specified time source. 119 * 120 * @since 15.0 121 */ 122 public static Stopwatch createStarted(Ticker ticker) { 123 return new Stopwatch(ticker).start(); 124 } 125 126 Stopwatch() { 127 this.ticker = Ticker.systemTicker(); 128 } 129 130 Stopwatch(Ticker ticker) { 131 this.ticker = checkNotNull(ticker, "ticker"); 132 } 133 134 /** 135 * Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()} 136 * has not been called since the last call to {@code start()}. 137 */ 138 public boolean isRunning() { 139 return isRunning; 140 } 141 142 /** 143 * Starts the stopwatch. 144 * 145 * @return this {@code Stopwatch} instance 146 * @throws IllegalStateException if the stopwatch is already running. 147 */ 148 @CanIgnoreReturnValue 149 public Stopwatch start() { 150 checkState(!isRunning, "This stopwatch is already running."); 151 isRunning = true; 152 startTick = ticker.read(); 153 return this; 154 } 155 156 /** 157 * Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this 158 * point. 159 * 160 * @return this {@code Stopwatch} instance 161 * @throws IllegalStateException if the stopwatch is already stopped. 162 */ 163 @CanIgnoreReturnValue 164 public Stopwatch stop() { 165 long tick = ticker.read(); 166 checkState(isRunning, "This stopwatch is already stopped."); 167 isRunning = false; 168 elapsedNanos += tick - startTick; 169 return this; 170 } 171 172 /** 173 * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 174 * 175 * @return this {@code Stopwatch} instance 176 */ 177 @CanIgnoreReturnValue 178 public Stopwatch reset() { 179 elapsedNanos = 0; 180 isRunning = false; 181 return this; 182 } 183 184 private long elapsedNanos() { 185 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 186 } 187 188 /** 189 * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 190 * with any fraction rounded down. 191 * 192 * <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally 193 * not useful to specify {@link TimeUnit#NANOSECONDS} precision here. 194 * 195 * <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent 196 * elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a 197 * strongly-typed {@link Duration} instance. 198 * 199 * @since 14.0 (since 10.0 as {@code elapsedTime()}) 200 */ 201 public long elapsed(TimeUnit desiredUnit) { 202 return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 203 } 204 205 /** 206 * Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link 207 * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 208 * 209 * @since 22.0 210 */ 211 @GwtIncompatible 212 @J2ObjCIncompatible 213 public Duration elapsed() { 214 return Duration.ofNanos(elapsedNanos()); 215 } 216 217 /** Returns a string representation of the current elapsed time. */ 218 @Override 219 public String toString() { 220 long nanos = elapsedNanos(); 221 222 TimeUnit unit = chooseUnit(nanos); 223 double value = (double) nanos / NANOSECONDS.convert(1, unit); 224 225 // Too bad this functionality is not exposed as a regular method call 226 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 227 } 228 229 private static TimeUnit chooseUnit(long nanos) { 230 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 231 return DAYS; 232 } 233 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 234 return HOURS; 235 } 236 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 237 return MINUTES; 238 } 239 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 240 return SECONDS; 241 } 242 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 243 return MILLISECONDS; 244 } 245 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 246 return MICROSECONDS; 247 } 248 return NANOSECONDS; 249 } 250 251 private static String abbreviate(TimeUnit unit) { 252 switch (unit) { 253 case NANOSECONDS: 254 return "ns"; 255 case MICROSECONDS: 256 return "\u03bcs"; // μs 257 case MILLISECONDS: 258 return "ms"; 259 case SECONDS: 260 return "s"; 261 case MINUTES: 262 return "min"; 263 case HOURS: 264 return "h"; 265 case DAYS: 266 return "d"; 267 default: 268 throw new AssertionError(); 269 } 270 } 271}