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