Skip to content

Instantly share code, notes, and snippets.

@P7h
Created January 29, 2014 16:01
Embed
What would you like to do?
Sample example demonstrating usage of Stopwatch API of Google Guava.
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
/**
* Sample example demonstrating usage of Stopwatch API of Google Guava.
*
* @see <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html">Guava Stopwatch</a>
*/
public final class StopwatchExample {
public final static void main(final String[] args) {
//Effective Guava v15.0, this is the one way of creating a Stopwatch instance.
final Stopwatch stopwatch = Stopwatch.createStarted();
//Sleep for few random milliseconds.
try {
Thread.sleep(new Random().nextInt(1000));
} catch (final InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
stopwatch.stop(); //optional
System.out.println("Elapsed time ==> " + stopwatch);
System.out.println("Elapsed time in Nanoseconds ==> " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
System.out.println("Elapsed time in Microseconds ==> " + stopwatch.elapsed(TimeUnit.MICROSECONDS));
System.out.println("Elapsed time in Milliseconds ==> " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
//System.out.println("Elapsed time in Seconds ==> " + stopwatch.elapsed(TimeUnit.SECONDS));
//System.out.println("Elapsed time in Minutes ==> " + stopwatch.elapsed(TimeUnit.MINUTES));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment