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 a string representation of the current elapsed time. 215 */ 216 @GwtIncompatible("String.format()") 217 @Override public String toString() { 218 long nanos = elapsedNanos(); 219 220 TimeUnit unit = chooseUnit(nanos); 221 double value = (double) nanos / NANOSECONDS.convert(1, unit); 222 223 // Too bad this functionality is not exposed as a regular method call 224 return String.format("%.4g %s", value, abbreviate(unit)); 225 } 226 227 private static TimeUnit chooseUnit(long nanos) { 228 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 229 return DAYS; 230 } 231 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 232 return HOURS; 233 } 234 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 235 return MINUTES; 236 } 237 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 238 return SECONDS; 239 } 240 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 241 return MILLISECONDS; 242 } 243 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 244 return MICROSECONDS; 245 } 246 return NANOSECONDS; 247 } 248 249 private static String abbreviate(TimeUnit unit) { 250 switch (unit) { 251 case NANOSECONDS: 252 return "ns"; 253 case MICROSECONDS: 254 return "\u03bcs"; // μs 255 case MILLISECONDS: 256 return "ms"; 257 case SECONDS: 258 return "s"; 259 case MINUTES: 260 return "min"; 261 case HOURS: 262 return "h"; 263 case DAYS: 264 return "d"; 265 default: 266 throw new AssertionError(); 267 } 268 } 269}