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