Java Reference
In-Depth Information
for
for ( int
int i = 0 ; i < nLoops ; i ++) {
l = fibImpl1 ( 50 );
}
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 ;
}
This may seem simple, but there are many problems with this code.
Microbenchmarks must use their results
The biggest problem with this code is that it never actually changes any program state. Be-
cause the result of the Fibonacci calculation is never used, the compiler is free to discard that
calculation. A smart compiler (including current Java 7 and 8 compilers) will end up execut-
ing this code:
long
long then = System . currentTimeMillis ();
long
long now = System . currentTimeMillis ();
System . out . println ( "Elapsed time: " + ( now - then ));
As a result, the elapsed time will be only a few milliseconds, regardless of the implementa-
tion of the Fibonacci method, or the number of times the loop is supposed to be executed.
Details of how the loop is eliminated are given in Chapter 4 .
There is a way around that particular issue: ensure that each result is read, not simply written.
In practice, changing the definition of l from a local variable to an instance variable (de-
clared with the volatile keyword) will allow the performance of the method to be meas-
ured. (The reason the l instance variable must be declared as volatile can be found in
Chapter 9 . )
Search WWH ::




Custom Search