How can I speed up this cycle?

How to speed up this loop (in C)?

unsigned int x = 50000000; double a= 0.9; double b= -0.9; for ( unsigned int i = 1; i <= x; i++) { a *= 0.9; //power b -= a/i; } 

Lead time: 14.000 s

I do not know why, but when I add these 2 lines to the code, the runtime is only 1.000 s.

 unsigned int x = 50000000; double a= 0.9; double b= -0.9; for ( unsigned int i = 1; i <= x; i++) { a *= 0.9; //power a += 10e250; a -=10e250; b -= a/i; } 

Thanks for any help

+6
source share
2 answers

Firstly, the most likely reason your code is running slower than expected is because a becomes a denormalized number. And denormalized numbers are a special case that can work much, much slower. It is also possible that adding 10 ^ 251 and subtracting it again, you change a to 0 and divide zero by something faster (since the result does not need to be calculated).

But real speed is not stupid, adding tiny, tiny numbers that have no effect. When x = several hundred, a will be so small that subtracting a / i from b will not make any difference. Therefore, instead of b - = a / i; you write

 double old_b = b; b -= a / i; if (b == old_b) break; 

and your time will change from seconds to much less than a millisecond.

+6
source

Adding this 10e250 exceeds the limit of the digits that a double variable can support, and when subtracting it will always be 0. Not sure about this, but multiplying should take more time than adding, which slows it down, for example. if you try this:

 for ( unsigned int i = 1; i <= x; i++) { a ++; //power b -= a/i; } 

You will see that it will work like a second time. I assume that when you add this 10e250 and after creating a = 0; multiplication with 0 is faster than with another nonzero variable.

0
source

All Articles