4

Possible Duplicate:
Is it faster to count down than it is to count up?

I was reading a C++ book called C++ for You++. (I have the 1998 edition.)

In the chapter about Monte Carlo Methods there's a snippet of code used to calculate definite integrals:

for(n = nPoints; n > 0; n--) {                    // A loop that goes down to
    x = a + double(rand()) * ((b-a) / RAND_MAX); // 0 is slightly more efficient.
    y = ...
    ... // if (y <= f(x)) increment count
    ...
}

My question is not about the code, rather about the comment:

A loop that goes down to 0 is slightly more efficient.

Is this true?????

Why would a loop going down to zero be more efficient than an ascending loop?

n, the loop counter, is not even used in the loop!

Again, this is not a pressing question. I am simply curious. I may have stumbled on a way to make my programs slightly more efficient!

Community
  • 1
  • 1
eboix
  • 5,113
  • 1
  • 27
  • 38

1 Answers1

6

I would expect that on a current processor, the effect would be negligible at best. However, it's worth noting that processors have dedicated instructions for comparison to zero, which logically might be faster than comparison to a variable and might save a register. Thus, strictly speaking, it would be faster because the processor has an in-built special case for it.

Puppy
  • 144,682
  • 38
  • 256
  • 465