简体   繁体   中英

How can I speed-up this loop?

How can I 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;
}

Execution time: 14.000 s

I don't know why, but when I add this 2 lines in code, execution time 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

First, the most likely reason why your code is running slower than expected is that a becomes a denormalised number. And denormalised numbers are a special case that may run a lot, lot slower. It is also possible that by adding 10^251 and subtracting it again you change a to 0 and dividing zero by anything is faster (since the result doesn't need to be calculated).

But the real speed up comes from not stupidly adding tiny, tiny numbers that have no effect whatsoever. When x = a few hundred, a will be so small that subtracting a/i from b will not make any difference. So 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.

Adding that 10e250 it exceeds the limit of digits the double variable can support and when subtracting it will always become 0. Not sure about this but multiplication should take more time than addition so it's slowing it down, ex. if you try this :

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

You will see that it will run like the second time. I guess that when you add that 10e250 and after making a = 0; the multiplication with 0 is faster then with other non-zero variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM