1

When testing an answer to one of my related questions, I wrote this:

public static long timeDouble(int iters) {
    long start = System.currentTimeMillis();
    for (; iters >=0; iters--) {
        double a = 1.2, b = 2.246, c = 4.4924, d = 8.98488, e = 17.969772;
        a = Math.sqrt(a);
        b = Math.cos(b);
        c = Math.sin(c);
        d = Math.tan(d);
        e = a + b - c * d / (e + 1);
        e = Math.pow(e, e);
    }
    return System.currentTimeMillis() - start;
}

This method's run time was an average of 414ms (using 1000000 iterations). However, something possessed me to add this line:

e = e + d - c * b / (a + 1);

immediately before e = Math.pow(e, e); With the addition of this line, the time for calculating this method dropped to an average of 206 ms (using the same test conditions).

What is causing this?

Community
  • 1
  • 1
ahodder
  • 11,353
  • 14
  • 71
  • 114
  • 1
    Maybe the value of `e` is decreased by that equation, and then `Math.pow(e, e)` will take less time to execute. – Eng.Fouad Jul 11 '12 at 16:24
  • 3
    It's probably due to the fact that Math.pow(e, e) is using less processor cycles, perhaps due to the fact that e is smaller. – Sam I am says Reinstate Monica Jul 11 '12 at 16:25
  • 2
    The above posters are probably correct, but I'd generally steer away from this kind of microbenchmarking, it has quite a few pitfalls. http://www.kdgregory.com/index.php?page=java.microBenchmark – Vala Jul 11 '12 at 16:29

1 Answers1

3

The values in the loop are constant, they don't depend on iters. and therefore the values are the same all the time.

    double a = 1.2, b = 2.246, c = 4.4924, d = 8.98488, e = 17.969772;
    a = Math.sqrt(a);
    b = Math.cos(b);
    c = Math.sin(c);
    d = Math.tan(d);
    e = a + b - c * d / (e + 1);
    e = Math.pow(e, e);

In the first version you were calculating e to be the value 17.969772 ^ 17.969772. In the second you are calculating e to be the value 0.69761863561124537 ^ 0.69761863561124537. This is (by your own evidence) easier to computer.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103