I'm working on a small project for the fibonacci algorithm.
I'm using the following method to calculate the algorithm. Note that elapsedTime() returns a double.
public static void fibonacciSequence(long n1, long n2) {
t0 = stopwatch.elapsedTime();
System.out.print("index: " + index + " -> " + n1 + "\t");
t1 = stopwatch.elapsedTime();
lapTime = (1000 * t1 - 1000 * t0) / 1000;
StdOut.println(" (" + lapTime + "\t " + t1 + ")");
if (index == stoppingPoint) {
return;
}
index++;
fibonacciSequence(n2, n1 + n2);
}
Now don't pay too much attention about the algorithm itself - it gets fixed. I only don't understand the formula for lapTime. Why can't it be
lapTime = t1-t0;
The expression you use for calculating the variable lapTime can be simplified, and you've posted the simplest representation it can have.
lapTime = (1000 * t1 - 1000 * t0) / 1000;
Can instead be :
lapTime = t1 - t0;
Which can be determined through simple algebra. It's even possible, given that t1 and t0 are double that the two expressions could result in a different value even if they mathematically equivalent. See here.
As far as the problem you're trying to solve, measuring the execution time of a Java program, there be dragons. Here's my own attempt at measuring with a micro-benchmark, which I ultimately believe was a failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With