Are downward loops better than upward loops?

Possible duplicate:
Is counting faster?

I read a book in C ++ called C ++ for You ++ . (I have a 1998 edition.)

The chapter on Monte Carlo methods has a code snippet used to calculate certain integrals:

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

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

A cycle that drops to 0 is somewhat more efficient.

It's true?????

Why is a cycle going to zero more efficient than an ascending cycle?

n , loop counter, not even used in a loop!

Again, this is not an urgent issue. I am just curious. Perhaps I came across something to make my programs a little more efficient!

+4
source share
1 answer

I would expect that on the current processor the effect would be negligible at best. However, it is worth noting that processors have special instructions for comparing with zero, which logically can be faster than comparing with a variable and can save the register. Thus, strictly speaking, this would be faster, because the processor has a built-in special case for it.

+6
source

Source: https://habr.com/ru/post/1388821/


All Articles