Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.base;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 import static java.util.concurrent.TimeUnit.MICROSECONDS;
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static java.util.concurrent.TimeUnit.NANOSECONDS;
 import static java.util.concurrent.TimeUnit.SECONDS;
 
 
An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using this class instead of direct calls to java.lang.System.nanoTime() for a few reasons:
  • An alternate time source can be substituted, for testing or performance reasons.
  • As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp returned by nanoTime at a different time. Stopwatch is a more effective abstraction because it exposes only these relative values, not the absolute ones.

Basic usage:

   Stopwatch stopwatch = new Stopwatch().start();
   doSomething();
   stopwatch.stop(); // optional

   long millis = stopwatch.elapsedMillis();

   log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
 

Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is already in the desired state.

When testing code that uses this class, use the Stopwatch(com.google.common.base.Ticker) to supply a fake or mock ticker. This allows you to simulate any valid behavior of the stopwatch.

Note: This class is not thread-safe.

Author(s):
Kevin Bourrillion
Since:
10.0
 
 @GwtCompatible(emulated=true)
 public final class Stopwatch {
   private final Ticker ticker;
   private boolean isRunning;
   private long elapsedNanos;
   private long startTick;

  
Creates (but does not start) a new stopwatch using java.lang.System.nanoTime() as its time source.
 
   public Stopwatch() {
     this(Ticker.systemTicker());
   }

  
Creates (but does not start) a new stopwatch, using the specified time source.
 
   public Stopwatch(Ticker ticker) {
     this. = checkNotNull(ticker);
   }

  
Returns true if start() has been called on this stopwatch, and stop() has not been called since the last call to start().
 
  public boolean isRunning() {
    return ;
  }

  
Starts the stopwatch.

Returns:
this Stopwatch instance
Throws:
java.lang.IllegalStateException if the stopwatch is already running.
  public Stopwatch start() {
     = true;
     = .read();
    return this;
  }

  
Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this point.

Returns:
this Stopwatch instance
Throws:
java.lang.IllegalStateException if the stopwatch is already stopped.
  public Stopwatch stop() {
    long tick = .read();
     = false;
     += tick - ;
    return this;
  }

  
Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.

Returns:
this Stopwatch instance
  public Stopwatch reset() {
     = 0;
     = false;
    return this;
  }
  private long elapsedNanos() {
    return  ? .read() -  +  : ;
  }

  
Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Note that the overhead of measurement can be more than a microsecond, so it is generally not useful to specify java.util.concurrent.TimeUnit.NANOSECONDS precision here.

  public long elapsedTime(TimeUnit desiredUnit) {
    return desiredUnit.convert(elapsedNanos(), );
  }

  
Returns the current elapsed time shown on this stopwatch, expressed in milliseconds, with any fraction rounded down. This is identical to elapsedTime(TimeUnit.MILLISECONDS.
  public long elapsedMillis() {
    return elapsedTime();
  }

  
Returns a string representation of the current elapsed time.
  @GwtIncompatible("String.format()")
  @Override public String toString() {
    return toString(4);
  }

  
Returns a string representation of the current elapsed time, choosing an appropriate unit and using the specified number of significant figures. For example, at the instant when elapsedTime(NANOSECONDS) would return {1234567}, toString(4) returns "1.235 ms".

Deprecated:
Use toString() instead. This method is scheduled to be removed in Guava release 15.0.
  @GwtIncompatible("String.format()")
  public String toString(int significantDigits) {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (doublenanos / .convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format("%." + significantDigits + "g %s",
        valueabbreviate(unit));
  }
  private static TimeUnit chooseUnit(long nanos) {
    if (.convert(nanos) > 0) {
      return ;
    }
    if (.convert(nanos) > 0) {
      return ;
    }
    if (.convert(nanos) > 0) {
      return ;
    }
    return ;
  }
  private static String abbreviate(TimeUnit unit) {
    switch (unit) {
      case :
        return "ns";
      case :
        return "\u03bcs"// μs
      case :
        return "ms";
      case :
        return "s";
      default:
        throw new AssertionError();
    }
  }
New to GrepCode? Check out our FAQ X