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(); // requires API Level 17
081 *        }
082 *      });
083 * }</pre>
084 *
085 * @author Kevin Bourrillion
086 * @since 10.0
087 */
088@GwtCompatible(emulated = true)
089@SuppressWarnings("GoodTime") // lots of violations
090@ElementTypesAreNonnullByDefault
091public final class Stopwatch {
092  private final Ticker ticker;
093  private boolean isRunning;
094  private long elapsedNanos;
095  private long startTick;
096
097  /**
098   * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source.
099   *
100   * @since 15.0
101   */
102  public static Stopwatch createUnstarted() {
103    return new Stopwatch();
104  }
105
106  /**
107   * Creates (but does not start) a new stopwatch, using the specified time source.
108   *
109   * @since 15.0
110   */
111  public static Stopwatch createUnstarted(Ticker ticker) {
112    return new Stopwatch(ticker);
113  }
114
115  /**
116   * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source.
117   *
118   * @since 15.0
119   */
120  public static Stopwatch createStarted() {
121    return new Stopwatch().start();
122  }
123
124  /**
125   * Creates (and starts) a new stopwatch, using the specified time source.
126   *
127   * @since 15.0
128   */
129  public static Stopwatch createStarted(Ticker ticker) {
130    return new Stopwatch(ticker).start();
131  }
132
133  Stopwatch() {
134    this.ticker = Ticker.systemTicker();
135  }
136
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, and {@link #stop()}
143   * has not been called since the last call to {@code start()}.
144   */
145  public boolean isRunning() {
146    return isRunning;
147  }
148
149  /**
150   * Starts the stopwatch.
151   *
152   * @return this {@code Stopwatch} instance
153   * @throws IllegalStateException if the stopwatch is already running.
154   */
155  @CanIgnoreReturnValue
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 elapsed up to this
165   * point.
166   *
167   * @return this {@code Stopwatch} instance
168   * @throws IllegalStateException if the stopwatch is already stopped.
169   */
170  @CanIgnoreReturnValue
171  public Stopwatch stop() {
172    long tick = ticker.read();
173    checkState(isRunning, "This stopwatch is already stopped.");
174    isRunning = false;
175    elapsedNanos += tick - startTick;
176    return this;
177  }
178
179  /**
180   * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.
181   *
182   * @return this {@code Stopwatch} instance
183   */
184  @CanIgnoreReturnValue
185  public Stopwatch reset() {
186    elapsedNanos = 0;
187    isRunning = false;
188    return this;
189  }
190
191  private long elapsedNanos() {
192    return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
193  }
194
195  /**
196   * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit,
197   * with any fraction rounded down.
198   *
199   * <p>Note that the overhead of measurement can be more than a microsecond, so it is generally not
200   * useful to specify {@link TimeUnit#NANOSECONDS} 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  /** Returns a string representation of the current elapsed time. */
209  @Override
210  public String toString() {
211    long nanos = elapsedNanos();
212
213    TimeUnit unit = chooseUnit(nanos);
214    double value = (double) nanos / NANOSECONDS.convert(1, unit);
215
216    // Too bad this functionality is not exposed as a regular method call
217    return Platform.formatCompact4Digits(value) + " " + abbreviate(unit);
218  }
219
220  private static TimeUnit chooseUnit(long nanos) {
221    if (DAYS.convert(nanos, NANOSECONDS) > 0) {
222      return DAYS;
223    }
224    if (HOURS.convert(nanos, NANOSECONDS) > 0) {
225      return HOURS;
226    }
227    if (MINUTES.convert(nanos, NANOSECONDS) > 0) {
228      return MINUTES;
229    }
230    if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
231      return SECONDS;
232    }
233    if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
234      return MILLISECONDS;
235    }
236    if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
237      return MICROSECONDS;
238    }
239    return NANOSECONDS;
240  }
241
242  private static String abbreviate(TimeUnit unit) {
243    switch (unit) {
244      case NANOSECONDS:
245        return "ns";
246      case MICROSECONDS:
247        return "\u03bcs"; // μs
248      case MILLISECONDS:
249        return "ms";
250      case SECONDS:
251        return "s";
252      case MINUTES:
253        return "min";
254      case HOURS:
255        return "h";
256      case DAYS:
257        return "d";
258      default:
259        throw new AssertionError();
260    }
261  }
262}