001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.base;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkState;
021import static java.util.concurrent.TimeUnit.MICROSECONDS;
022import static java.util.concurrent.TimeUnit.MILLISECONDS;
023import static java.util.concurrent.TimeUnit.NANOSECONDS;
024import static java.util.concurrent.TimeUnit.SECONDS;
025
026import com.google.common.annotations.Beta;
027import com.google.common.annotations.GwtCompatible;
028import com.google.common.annotations.GwtIncompatible;
029
030import java.util.concurrent.TimeUnit;
031
032/**
033 * An object that measures elapsed time in nanoseconds. It is useful to measure
034 * elapsed time using this class instead of direct calls to {@link
035 * System#nanoTime} for a few reasons:
036 *
037 * <ul>
038 * <li>An alternate time source can be substituted, for testing or performance
039 *     reasons.
040 * <li>As documented by {@code nanoTime}, the value returned has no absolute
041 *     meaning, and can only be interpreted as relative to another timestamp
042 *     returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
043 *     more effective abstraction because it exposes only these relative values,
044 *     not the absolute ones.
045 * </ul>
046 *
047 * <p>Basic usage:
048 * <pre>
049 *   Stopwatch stopwatch = Stopwatch.{@link #createStarted createStarted}();
050 *   doSomething();
051 *   stopwatch.{@link #stop stop}(); // optional
052 *
053 *   long millis = stopwatch.elapsed(MILLISECONDS);
054 *
055 *   log.info("time: " + stopwatch); // formatted string like "12.3 ms"</pre>
056 *
057 * <p>Stopwatch methods are not idempotent; it is an error to start or stop a
058 * stopwatch that is already in the desired state.
059 *
060 * <p>When testing code that uses this class, use
061 * {@link #createUnstarted(Ticker)} or {@link #createStarted(Ticker)} to
062 * supply a fake or mock ticker.
063 * <!-- TODO(kevinb): restore the "such as" --> This allows you to
064 * simulate any valid behavior of the stopwatch.
065 *
066 * <p><b>Note:</b> This class is not thread-safe.
067 *
068 * @author Kevin Bourrillion
069 * @since 10.0
070 */
071@Beta
072@GwtCompatible(emulated = true)
073public final class Stopwatch {
074  private final Ticker ticker;
075  private boolean isRunning;
076  private long elapsedNanos;
077  private long startTick;
078
079  /**
080   * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
081   * as its time source.
082   *
083   * @since 15.0
084   */
085  public static Stopwatch createUnstarted() {
086    return new Stopwatch();
087  }
088
089  /**
090   * Creates (but does not start) a new stopwatch, using the specified time
091   * source.
092   *
093   * @since 15.0
094   */
095  public static Stopwatch createUnstarted(Ticker ticker) {
096    return new Stopwatch(ticker);
097  }
098
099  /**
100   * Creates (and starts) a new stopwatch using {@link System#nanoTime}
101   * as its time source.
102   *
103   * @since 15.0
104   */
105  public static Stopwatch createStarted() {
106    return new Stopwatch().start();
107  }
108
109  /**
110   * Creates (and starts) a new stopwatch, using the specified time
111   * source.
112   *
113   * @since 15.0
114   */
115  public static Stopwatch createStarted(Ticker ticker) {
116    return new Stopwatch(ticker).start();
117  }
118
119  /**
120   * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
121   * as its time source.
122   *
123   * @deprecated Use {@link Stopwatch#createUnstarted()} instead.
124   */
125  @Deprecated
126  Stopwatch() {
127    this(Ticker.systemTicker());
128  }
129
130  /**
131   * Creates (but does not start) a new stopwatch, using the specified time
132   * source.
133   *
134   * @deprecated Use {@link Stopwatch#createUnstarted(Ticker)} instead.
135   */
136  @Deprecated
137  Stopwatch(Ticker ticker) {
138    this.ticker = checkNotNull(ticker, "ticker");
139  }
140
141  /**
142   * Returns {@code true} if {@link #start()} has been called on this stopwatch,
143   * and {@link #stop()} has not been called since the last call to {@code
144   * start()}.
145   */
146  public boolean isRunning() {
147    return isRunning;
148  }
149
150  /**
151   * Starts the stopwatch.
152   *
153   * @return this {@code Stopwatch} instance
154   * @throws IllegalStateException if the stopwatch is already running.
155   */
156  public Stopwatch start() {
157    checkState(!isRunning, "This stopwatch is already running.");
158    isRunning = true;
159    startTick = ticker.read();
160    return this;
161  }
162
163  /**
164   * Stops the stopwatch. Future reads will return the fixed duration that had
165   * elapsed up to this point.
166   *
167   * @return this {@code Stopwatch} instance
168   * @throws IllegalStateException if the stopwatch is already stopped.
169   */
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,
180   * and places it in a stopped state.
181   *
182   * @return this {@code Stopwatch} instance
183   */
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
196   * in the desired time unit, with any fraction rounded down.
197   *
198   * <p>Note that the overhead of measurement can be more than a microsecond, so
199   * it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
200   * precision here.
201   *
202   * @since 14.0 (since 10.0 as {@code elapsedTime()})
203   */
204  public long elapsed(TimeUnit desiredUnit) {
205    return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
206  }
207
208  /**
209   * Returns a string representation of the current elapsed time.
210   */
211  @GwtIncompatible("String.format()")
212  @Override public String toString() {
213    long nanos = elapsedNanos();
214
215    TimeUnit unit = chooseUnit(nanos);
216    double value = (double) nanos / NANOSECONDS.convert(1, unit);
217
218    // Too bad this functionality is not exposed as a regular method call
219    return String.format("%.4g %s", value, abbreviate(unit));
220  }
221
222  private static TimeUnit chooseUnit(long nanos) {
223    if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
224      return SECONDS;
225    }
226    if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
227      return MILLISECONDS;
228    }
229    if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
230      return MICROSECONDS;
231    }
232    return NANOSECONDS;
233  }
234
235  private static String abbreviate(TimeUnit unit) {
236    switch (unit) {
237      case NANOSECONDS:
238        return "ns";
239      case MICROSECONDS:
240        return "\u03bcs"; // μs
241      case MILLISECONDS:
242        return "ms";
243      case SECONDS:
244        return "s";
245      default:
246        throw new AssertionError();
247    }
248  }
249}