1.19. Measuring Time
Problem
You need to determine how much time has elapsed during the execution of a block of code.
Solution
Use
StopWatch
to measure the time it takes to execute a section of code. Example 1-20 demonstrates the use of this class to measure
the time it takes to perform simple arithmetic operations.
Example 1-20. Using StopWatch to measure time
import org.apache.commons.lang.time.StopWatch;
StopWatch clock = new StopWatch( );
System.out.println("Time to Math.sin(0.34) ten million times?" );
clock.start( );
for( int i = 0; i < 100000000; i++ ) {
Math.sin( 0.34 );
}
clock.stop( );
System.out.println( "It takes " + clock.getTime( ) + " milliseconds" );
clock.reset( );
System.out.println( "How long to multiply 2 doubles one billion times?" );
clock.start( );
for( int i = 0; i < 1000000000; i++) {
double result = 3423.2234 * 23e-4;
}
clock.stop( );
System.out.println( "It takes " + clock.getTime( ) + " milliseconds." );This example measures execution time with
StopWatch and produces the following output:
Time to Math.sin(0.34) ten million times? It takes 6865 milliseconds How long to multiply 2 doubles one billion times? It takes 1992 milliseconds.
Discussion
StopWatch performs the same functions as a
physical stop watch; you can start, stop, pause, resume, reset, and
split the clock. The name of this utility conveys unmistakable
meaning: starting, stopping, pausing, and resuming a clock are
methods that need no explanation, and resetting an instance of
StopWatch simply resets ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access