Java, XML, & Literate Programming
by Andrew Dwelly

Listing One
<SECTION TITLE="The Nfib algorithm">
<NARRATIVE>
<P>Nfib is our next example of benchmarking algorithms, it is closely
related to the Fibonacci series, and gives
a broad idea of the speed of procedure calls in the interpreter. It
relies on its rather peculiar property
that the integer that it returns is the same as the number of procedure
calls needed to generate the number.</P>
<P>The Fibonacci series starts 1, 1, 2, 3, 5,... each element is the sum
of the two before. The <![CDATA[<B>NFIB</B>]]>
algorithm adds 1 at each stage giving the series 1, 1, 3, 5, 9,... Thus
counting from 0, we can see that nfib(3) = 5.
Here is the code for the method:</P>
</NARRATIVE>
<CODE NAME="nfib" EXTENDS="Benchmark" WEIGHT="70">
 public int nfib(int n) {
     if (n &lt; 2) {
  return 1;
     } else {
         return nfib(n - 1) + nfib(n - 2) + 1;
     }
 }
</CODE>
<NARRATIVE>
<P>It's quite easy to see that nfib(2) takes exactly three calls to nfib
to calculate its return value of 3.
To get a very rough idea of procedure call speed, simply divide the time
taken to calculate a relatively large
<REF PATH ="#nfib">nfib</REF> number (e.g, nfib(37)) by the return
value.</P>
<P>The algorithm can be found as part of the benchmark class defined
here, which includes a user interface:</P>
</NARRATIVE>
<CLASS NAME = "Benchmark"
       EXTENDS = "JFrame"
       IMPLEMENTS = "ActionListener"
 PACKAGE = "com.cedillasoft.benchmarks"/>

Listing Two
<NARRATIVE>
<P>We are going to use the Java Foundation classes to create the user
interface so the awt and swing packages need to be imported in the
Benchmark class.</P>
</NARRATIVE>
<CODE NAME="imports" EXTENDS="Benchmark.prelude">
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
</CODE>






1


