简体   繁体   English

我怎样才能加快这个循环?

[英]How can I speed-up this loop?

How can I speed-up this loop (in C)? 如何加速此循环(在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 执行时间:14.000秒

I don't know why, but when I add this 2 lines in code, execution time is only 1.000 s. 我不知道为什么,但是当我在代码中添加这两行时,执行时间只有1.000秒。

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. 首先,代码运行速度低于预期的最可能原因是a变为非规范化数字。 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). 也可以通过添加10 ^ 251并再次减去它来将a更改为0并将零除以任何更快(因为不需要计算结果)。

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. 当x =几百时,a将是如此之小以至于从b中减去a / i将不会产生任何差异。 So instead of b -= a/i; 所以代替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. 添加10e250它超过了双变量可以支持的数字限制,当减去它时总是变为0.不确定这个,但乘法应该比加法花费更多的时间,所以它减慢了速度,例如。 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; 我想当你添加10e250并且在a = 0之后; the multiplication with 0 is faster then with other non-zero variable. 乘以0比使用其他非零变量快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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