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