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