Java Reference
In-Depth Information
for
for ( int
int i = 0 ; i < nLoops ; i ++) {
input [ i ] = r . nextInt ( 100 );
}
}
private
private void
void doTest ( boolean
boolean isWarmup ) {
long
long then = System . currentTimeMillis ();
for
for ( int
int i = 0 ; i < nLoops ; i ++) {
l = fibImpl1 ( input [ i ]);
}
iif (! isWarmup ) {
long
long now = System . currentTimeMillis ();
System . out . println ( "Elapsed time: " + ( now - then ));
}
}
private
private double
double fibImpl1 ( int
int n ) {
iif ( n < 0 ) throw
new IllegalArgumentException ( "Must be > 0" );
iif ( n == 0 ) return
throw new
return 0 d ;
iif ( n == 1 ) return
return 1 d ;
double
double d = fibImpl1 ( n - 2 ) + fibImpl ( n - 1 );
iif ( Double . isInfinite ( d )) throw
throw new
new ArithmeticException ( "Overflow" );
return
return d ;
}
}
Even this microbenchmark measures some things that are not germane to the Fibonacci im-
plementation: there is a certain amount of loop and method overhead in setting up the calls to
the fibImpl1() method, and the need to write each result to a volatile variable is addition-
al overhead.
Beware, too, of additional compilation effects. The compiler uses profile feedback of code to
determine the best optimizations to employ when compiling a method. The profile feedback
is based on which methods are frequently called, the stack depth when they are called, the
actual type (including subclasses) of their arguments, and so on—it is dependent on the en-
vironment in which the code actually runs. The compiler will frequently optimize code dif-
ferently in a microbenchmark than it optimizes that same code when used in an application.
If the same class measures a second implementation of the Fibonacci method, then all sorts
of compilation effects can occur, particularly if the implementation occurs in different
classes.
Finally, there is the issue of what the microbenchmark actually means. The overall time dif-
ference in a benchmark such as the one discussed here may be measured in seconds for a
Search WWH ::




Custom Search