Java, XML, & Literate Programming by Andrew Dwelly Listing One

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.

The Fibonacci series starts 1, 1, 2, 3, 5,... each element is the sum of the two before. The NFIB]]> 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:

public int nfib(int n) { if (n < 2) { return 1; } else { return nfib(n - 1) + nfib(n - 2) + 1; } }

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 nfib number (e.g, nfib(37)) by the return value.

The algorithm can be found as part of the benchmark class defined here, which includes a user interface:

Listing Two

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.

import java.awt.*; import java.awt.event.*; import javax.swing.*; 1