Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 705
Joozty Avatar asked Nov 25 '15 10:11

Joozty


1 Answers

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.

like image 66
gnasher729 Avatar answered Sep 30 '22 12:09

gnasher729