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