Coverage Summary for Class: Stopwatch (com.google.common.base)

Class Method, % Line, %
Stopwatch 18.8% (3/16) 15.4% (8/52)
Stopwatch$1 0% (0/1) 0% (0/1)
Total 17.6% (3/17) 15.1% (8/53)


1 /* 2  * Copyright (C) 2008 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5  * in compliance with the License. You may obtain a copy of the License at 6  * 7  * http://www.apache.org/licenses/LICENSE-2.0 8  * 9  * Unless required by applicable law or agreed to in writing, software distributed under the License 10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11  * or implied. See the License for the specific language governing permissions and limitations under 12  * the License. 13  */ 14  15 package com.google.common.base; 16  17 import static com.google.common.base.Preconditions.checkNotNull; 18 import static com.google.common.base.Preconditions.checkState; 19 import static java.util.concurrent.TimeUnit.DAYS; 20 import static java.util.concurrent.TimeUnit.HOURS; 21 import static java.util.concurrent.TimeUnit.MICROSECONDS; 22 import static java.util.concurrent.TimeUnit.MILLISECONDS; 23 import static java.util.concurrent.TimeUnit.MINUTES; 24 import static java.util.concurrent.TimeUnit.NANOSECONDS; 25 import static java.util.concurrent.TimeUnit.SECONDS; 26  27 import com.google.common.annotations.GwtCompatible; 28 import com.google.common.annotations.GwtIncompatible; 29 import com.google.errorprone.annotations.CanIgnoreReturnValue; 30 import com.google.j2objc.annotations.J2ObjCIncompatible; 31 import java.time.Duration; 32 import java.util.concurrent.TimeUnit; 33  34 /** 35  * An object that accurately measures <i>elapsed time</i>: the measured duration between two 36  * successive readings of "now" in the same process. 37  * 38  * <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like 39  * {@link System#currentTimeMillis()}, best represented as an {@link Instant}. Such values 40  * <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but 41  * doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings 42  * are inherently approximate, routinely affected by periodic clock corrections. Because this class 43  * (by default) uses {@link System#nanoTime}, it is unaffected by these changes. 44  * 45  * <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons: 46  * 47  * <ul> 48  * <li>The raw {@code long} values returned by {@code nanoTime} are meaningless and unsafe to use 49  * in any other way than how {@code Stopwatch} uses them. 50  * <li>An alternative source of nanosecond ticks can be substituted, for example for testing or 51  * performance reasons, without affecting most of your code. 52  * </ul> 53  * 54  * <p>Basic usage: 55  * 56  * <pre>{@code 57  * Stopwatch stopwatch = Stopwatch.createStarted(); 58  * doSomething(); 59  * stopwatch.stop(); // optional 60  * 61  * Duration duration = stopwatch.elapsed(); 62  * 63  * log.info("time: " + stopwatch); // formatted string like "12.3 ms" 64  * }</pre> 65  * 66  * <p>The state-changing methods are not idempotent; it is an error to start or stop a stopwatch 67  * that is already in the desired state. 68  * 69  * <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link 70  * #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid 71  * behavior of the stopwatch. 72  * 73  * <p><b>Note:</b> This class is not thread-safe. 74  * 75  * <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep 76  * time while the device is asleep. Instead, create one like this: 77  * 78  * <pre>{@code 79  * Stopwatch.createStarted( 80  * new Ticker() { 81  * public long read() { 82  * return android.os.SystemClock.elapsedRealtimeNanos(); 83  * } 84  * }); 85  * }</pre> 86  * 87  * @author Kevin Bourrillion 88  * @since 10.0 89  */ 90 @GwtCompatible(emulated = true) 91 @SuppressWarnings("GoodTime") // lots of violations 92 @ElementTypesAreNonnullByDefault 93 public final class Stopwatch { 94  private final Ticker ticker; 95  private boolean isRunning; 96  private long elapsedNanos; 97  private long startTick; 98  99  /** 100  * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 101  * 102  * @since 15.0 103  */ 104  public static Stopwatch createUnstarted() { 105  return new Stopwatch(); 106  } 107  108  /** 109  * Creates (but does not start) a new stopwatch, using the specified time source. 110  * 111  * @since 15.0 112  */ 113  public static Stopwatch createUnstarted(Ticker ticker) { 114  return new Stopwatch(ticker); 115  } 116  117  /** 118  * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 119  * 120  * @since 15.0 121  */ 122  public static Stopwatch createStarted() { 123  return new Stopwatch().start(); 124  } 125  126  /** 127  * Creates (and starts) a new stopwatch, using the specified time source. 128  * 129  * @since 15.0 130  */ 131  public static Stopwatch createStarted(Ticker ticker) { 132  return new Stopwatch(ticker).start(); 133  } 134  135  Stopwatch() { 136  this.ticker = Ticker.systemTicker(); 137  } 138  139  Stopwatch(Ticker ticker) { 140  this.ticker = checkNotNull(ticker, "ticker"); 141  } 142  143  /** 144  * Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()} 145  * has not been called since the last call to {@code start()}. 146  */ 147  public boolean isRunning() { 148  return isRunning; 149  } 150  151  /** 152  * Starts the stopwatch. 153  * 154  * @return this {@code Stopwatch} instance 155  * @throws IllegalStateException if the stopwatch is already running. 156  */ 157  @CanIgnoreReturnValue 158  public Stopwatch start() { 159  checkState(!isRunning, "This stopwatch is already running."); 160  isRunning = true; 161  startTick = ticker.read(); 162  return this; 163  } 164  165  /** 166  * Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this 167  * point. 168  * 169  * @return this {@code Stopwatch} instance 170  * @throws IllegalStateException if the stopwatch is already stopped. 171  */ 172  @CanIgnoreReturnValue 173  public Stopwatch stop() { 174  long tick = ticker.read(); 175  checkState(isRunning, "This stopwatch is already stopped."); 176  isRunning = false; 177  elapsedNanos += tick - startTick; 178  return this; 179  } 180  181  /** 182  * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 183  * 184  * @return this {@code Stopwatch} instance 185  */ 186  @CanIgnoreReturnValue 187  public Stopwatch reset() { 188  elapsedNanos = 0; 189  isRunning = false; 190  return this; 191  } 192  193  private long elapsedNanos() { 194  return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 195  } 196  197  /** 198  * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 199  * with any fraction rounded down. 200  * 201  * <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally 202  * not useful to specify {@link TimeUnit#NANOSECONDS} precision here. 203  * 204  * <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent 205  * elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a 206  * strongly-typed {@code Duration} instance. 207  * 208  * @since 14.0 (since 10.0 as {@code elapsedTime()}) 209  */ 210  public long elapsed(TimeUnit desiredUnit) { 211  return desiredUnit.convert(elapsedNanos(), NANOSECONDS); 212  } 213  214  /** 215  * Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link 216  * #elapsed(TimeUnit)}, this method does not lose any precision due to rounding. 217  * 218  * @since 22.0 219  */ 220  @GwtIncompatible 221  @J2ObjCIncompatible 222  public Duration elapsed() { 223  return Duration.ofNanos(elapsedNanos()); 224  } 225  226  /** Returns a string representation of the current elapsed time. */ 227  @Override 228  public String toString() { 229  long nanos = elapsedNanos(); 230  231  TimeUnit unit = chooseUnit(nanos); 232  double value = (double) nanos / NANOSECONDS.convert(1, unit); 233  234  // Too bad this functionality is not exposed as a regular method call 235  return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 236  } 237  238  private static TimeUnit chooseUnit(long nanos) { 239  if (DAYS.convert(nanos, NANOSECONDS) > 0) { 240  return DAYS; 241  } 242  if (HOURS.convert(nanos, NANOSECONDS) > 0) { 243  return HOURS; 244  } 245  if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 246  return MINUTES; 247  } 248  if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 249  return SECONDS; 250  } 251  if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 252  return MILLISECONDS; 253  } 254  if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 255  return MICROSECONDS; 256  } 257  return NANOSECONDS; 258  } 259  260  private static String abbreviate(TimeUnit unit) { 261  switch (unit) { 262  case NANOSECONDS: 263  return "ns"; 264  case MICROSECONDS: 265  return "\u03bcs"; // ?s 266  case MILLISECONDS: 267  return "ms"; 268  case SECONDS: 269  return "s"; 270  case MINUTES: 271  return "min"; 272  case HOURS: 273  return "h"; 274  case DAYS: 275  return "d"; 276  default: 277  throw new AssertionError(); 278  } 279  } 280 }