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