1/*
2 * Copyright (C) 2008 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.base;
18
19import static com.google.common.base.Preconditions.checkNotNull;
20import static com.google.common.base.Preconditions.checkState;
21import static java.util.concurrent.TimeUnit.MICROSECONDS;
22import static java.util.concurrent.TimeUnit.MILLISECONDS;
23import static java.util.concurrent.TimeUnit.NANOSECONDS;
24import static java.util.concurrent.TimeUnit.SECONDS;
25
26import com.google.common.annotations.Beta;
27import com.google.common.annotations.GwtCompatible;
28
29import java.util.concurrent.TimeUnit;
30
31/**
32 * An object that measures elapsed time in nanoseconds. It is useful to measure
33 * elapsed time using this class instead of direct calls to {@link
34 * System#nanoTime} for a few reasons:
35 *
36 * <ul>
37 * <li>An alternate time source can be substituted, for testing or performance
38 *     reasons.
39 * <li>As documented by {@code nanoTime}, the value returned has no absolute
40 *     meaning, and can only be interpreted as relative to another timestamp
41 *     returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
42 *     more effective abstraction because it exposes only these relative values,
43 *     not the absolute ones.
44 * </ul>
45 *
46 * <p>Basic usage:
47 * <pre>
48 *   Stopwatch stopwatch = new Stopwatch().{@link #start start}();
49 *   doSomething();
50 *   stopwatch.{@link #stop stop}(); // optional
51 *
52 *   long millis = stopwatch.{@link #elapsedMillis elapsedMillis}();
53 *
54 *   log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
55 * </pre>
56 *
57 * <p>Stopwatch methods are not idempotent; it is an error to start or stop a
58 * stopwatch that is already in the desired state.
59 *
60 * <p>When testing code that uses this class, use the {@linkplain
61 * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.
62 * <!-- TODO(kevinb): restore the "such as" --> This allows you to
63 * simulate any valid behavior of the stopwatch.
64 *
65 * <p><b>Note:</b> This class is not thread-safe.
66 *
67 * @author Kevin Bourrillion
68 * @since 10.0
69 */
70@Beta
71@GwtCompatible(emulated=true)
72public final class Stopwatch {
73  private final Ticker ticker;
74  private boolean isRunning;
75  private long elapsedNanos;
76  private long startTick;
77
78  /**
79   * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
80   * as its time source.
81   */
82  public Stopwatch() {
83    this(Ticker.systemTicker());
84  }
85
86  /**
87   * Creates (but does not start) a new stopwatch, using the specified time
88   * source.
89   */
90  public Stopwatch(Ticker ticker) {
91    this.ticker = checkNotNull(ticker);
92  }
93
94  /**
95   * Returns {@code true} if {@link #start()} has been called on this stopwatch,
96   * and {@link #stop()} has not been called since the last call to {@code
97   * start()}.
98   */
99  public boolean isRunning() {
100    return isRunning;
101  }
102
103  /**
104   * Starts the stopwatch.
105   *
106   * @return this {@code Stopwatch} instance
107   * @throws IllegalStateException if the stopwatch is already running.
108   */
109  public Stopwatch start() {
110    checkState(!isRunning);
111    isRunning = true;
112    startTick = ticker.read();
113    return this;
114  }
115
116  /**
117   * Stops the stopwatch. Future reads will return the fixed duration that had
118   * elapsed up to this point.
119   *
120   * @return this {@code Stopwatch} instance
121   * @throws IllegalStateException if the stopwatch is already stopped.
122   */
123  public Stopwatch stop() {
124    long tick = ticker.read();
125    checkState(isRunning);
126    isRunning = false;
127    elapsedNanos += tick - startTick;
128    return this;
129  }
130
131  /**
132   * Sets the elapsed time for this stopwatch to zero,
133   * and places it in a stopped state.
134   *
135   * @return this {@code Stopwatch} instance
136   */
137  public Stopwatch reset() {
138    elapsedNanos = 0;
139    isRunning = false;
140    return this;
141  }
142
143  private long elapsedNanos() {
144    return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
145  }
146
147  /**
148   * Returns the current elapsed time shown on this stopwatch, expressed
149   * in the desired time unit, with any fraction rounded down.
150   *
151   * <p>Note that the overhead of measurement can be more than a microsecond, so
152   * it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
153   * precision here.
154   */
155  public long elapsedTime(TimeUnit desiredUnit) {
156    return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
157  }
158
159  /**
160   * Returns the current elapsed time shown on this stopwatch, expressed
161   * in milliseconds, with any fraction rounded down. This is identical to
162   * {@code elapsedTime(TimeUnit.MILLISECONDS}.
163   */
164  public long elapsedMillis() {
165    return elapsedTime(MILLISECONDS);
166  }
167
168  private static TimeUnit chooseUnit(long nanos) {
169    if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
170      return SECONDS;
171    }
172    if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
173      return MILLISECONDS;
174    }
175    if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
176      return MICROSECONDS;
177    }
178    return NANOSECONDS;
179  }
180
181  private static String abbreviate(TimeUnit unit) {
182    switch (unit) {
183      case NANOSECONDS:
184        return "ns";
185      case MICROSECONDS:
186        return "\u03bcs"; // μs
187      case MILLISECONDS:
188        return "ms";
189      case SECONDS:
190        return "s";
191      default:
192        throw new AssertionError();
193    }
194  }
195}
196
197