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 accurately measures <i>elapsed time</i>: the measured duration between two 033 * successive readings of "now" in the same process. 034 * 035 * <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like 036 * {@link System#currentTimeMillis()}, best represented as an {@link java.time.Instant}. Such values 037 * <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but 038 * doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings 039 * are inherently approximate, routinely affected by periodic clock corrections. Because this class 040 * (by default) uses {@link System#nanoTime}, it is unaffected by these changes. 041 * 042 * <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons: 043 * 044 * <ul> 045 * <li>The raw {@code long} values returned by {@code nanoTime} are meaningless and unsafe to use 046 * in any other way than how {@code Stopwatch} uses them. 047 * <li>An alternative source of nanosecond ticks can be substituted, for example for testing or 048 * performance reasons, without affecting most of your code. 049 * </ul> 050 * 051 * <p>The one downside of {@code Stopwatch} relative to {@link System#nanoTime()} is that {@code 052 * Stopwatch} requires object allocation and additional method calls, which can reduce the accuracy 053 * of the elapsed times reported. {@code Stopwatch} is still suitable for logging and metrics where 054 * reasonably accurate values are sufficient. If the uncommon case that you need to maximize 055 * accuracy, use {@code System.nanoTime()} directly instead. 056 * 057 * <p>Basic usage: 058 * 059 * <pre>{@code 060 * Stopwatch stopwatch = Stopwatch.createStarted(); 061 * doSomething(); 062 * stopwatch.stop(); // optional 063 * 064 * long millis = stopwatch.elapsed(MILLISECONDS); 065 * 066 * log.info("time: " + stopwatch); // formatted string like "12.3 ms" 067 * }</pre> 068 * 069 * <p>The state-changing methods are not idempotent; it is an error to start or stop a stopwatch 070 * that is already in the desired state. 071 * 072 * <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link 073 * #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid 074 * behavior of the stopwatch. 075 * 076 * <p><b>Note:</b> This class is not thread-safe. 077 * 078 * <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep 079 * time while the device is asleep. Instead, create one like this: 080 * 081 * <pre>{@code 082 * Stopwatch.createStarted( 083 * new Ticker() { 084 * public long read() { 085 * return android.os.SystemClock.elapsedRealtimeNanos(); // requires API Level 17 086 * } 087 * }); 088 * }</pre> 089 * 090 * @author Kevin Bourrillion 091 * @since 10.0 092 */ 093@GwtCompatible(emulated = true) 094@SuppressWarnings("GoodTime") // lots of violations 095@ElementTypesAreNonnullByDefault 096public final class Stopwatch { 097 private final Ticker ticker; 098 private boolean isRunning; 099 private long elapsedNanos; 100 private long startTick; 101 102 /** 103 * Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source. 104 * 105 * @since 15.0 106 */ 107 public static Stopwatch createUnstarted() { 108 return new Stopwatch(); 109 } 110 111 /** 112 * Creates (but does not start) a new stopwatch, using the specified time source. 113 * 114 * @since 15.0 115 */ 116 public static Stopwatch createUnstarted(Ticker ticker) { 117 return new Stopwatch(ticker); 118 } 119 120 /** 121 * Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source. 122 * 123 * @since 15.0 124 */ 125 public static Stopwatch createStarted() { 126 return new Stopwatch().start(); 127 } 128 129 /** 130 * Creates (and starts) a new stopwatch, using the specified time source. 131 * 132 * @since 15.0 133 */ 134 public static Stopwatch createStarted(Ticker ticker) { 135 return new Stopwatch(ticker).start(); 136 } 137 138 Stopwatch() { 139 this.ticker = Ticker.systemTicker(); 140 } 141 142 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, and {@link #stop()} 148 * has not been called since the last call to {@code start()}. 149 */ 150 public boolean isRunning() { 151 return isRunning; 152 } 153 154 /** 155 * Starts the stopwatch. 156 * 157 * @return this {@code Stopwatch} instance 158 * @throws IllegalStateException if the stopwatch is already running. 159 */ 160 @CanIgnoreReturnValue 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 elapsed up to this 170 * point. 171 * 172 * @return this {@code Stopwatch} instance 173 * @throws IllegalStateException if the stopwatch is already stopped. 174 */ 175 @CanIgnoreReturnValue 176 public Stopwatch stop() { 177 long tick = ticker.read(); 178 checkState(isRunning, "This stopwatch is already stopped."); 179 isRunning = false; 180 elapsedNanos += tick - startTick; 181 return this; 182 } 183 184 /** 185 * Sets the elapsed time for this stopwatch to zero, and places it in a stopped state. 186 * 187 * @return this {@code Stopwatch} instance 188 */ 189 @CanIgnoreReturnValue 190 public Stopwatch reset() { 191 elapsedNanos = 0; 192 isRunning = false; 193 return this; 194 } 195 196 private long elapsedNanos() { 197 return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; 198 } 199 200 /** 201 * Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, 202 * with any fraction rounded down. 203 * 204 * <p>Note that the overhead of measurement can be more than a microsecond, so it is generally not 205 * useful to specify {@link TimeUnit#NANOSECONDS} 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 /** Returns a string representation of the current elapsed time. */ 214 @Override 215 public String toString() { 216 long nanos = elapsedNanos(); 217 218 TimeUnit unit = chooseUnit(nanos); 219 double value = (double) nanos / NANOSECONDS.convert(1, unit); 220 221 // Too bad this functionality is not exposed as a regular method call 222 return Platform.formatCompact4Digits(value) + " " + abbreviate(unit); 223 } 224 225 private static TimeUnit chooseUnit(long nanos) { 226 if (DAYS.convert(nanos, NANOSECONDS) > 0) { 227 return DAYS; 228 } 229 if (HOURS.convert(nanos, NANOSECONDS) > 0) { 230 return HOURS; 231 } 232 if (MINUTES.convert(nanos, NANOSECONDS) > 0) { 233 return MINUTES; 234 } 235 if (SECONDS.convert(nanos, NANOSECONDS) > 0) { 236 return SECONDS; 237 } 238 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { 239 return MILLISECONDS; 240 } 241 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { 242 return MICROSECONDS; 243 } 244 return NANOSECONDS; 245 } 246 247 private static String abbreviate(TimeUnit unit) { 248 switch (unit) { 249 case NANOSECONDS: 250 return "ns"; 251 case MICROSECONDS: 252 return "\u03bcs"; // μs 253 case MILLISECONDS: 254 return "ms"; 255 case SECONDS: 256 return "s"; 257 case MINUTES: 258 return "min"; 259 case HOURS: 260 return "h"; 261 case DAYS: 262 return "d"; 263 default: 264 throw new AssertionError(); 265 } 266 } 267}