简体   繁体   English

+ =比-=快吗?

[英]Is += faster than -=?

Full disclosure - I was inspired by Is x += a quicker than x = x + a? 全面披露-我的灵感来自x + =比x = x + a快吗?

That aside, I decided to test += vs -= . 除此之外,我决定测试+= vs- -= Simple tests reveal they're about the same. 简单的测试表明它们大致相同。 Then I tried something similar to: 然后我尝试了类似的东西:

std::vector<int> x;
for (int i = 0 ; i < 10000 ; i++)
   x.push_back(rand()%10);

and call += and -= proportionally to a given number: 然后按给定数字按比例调用+=-=

long long sum = 0;

for ( each number in the array )
    if ( x[j] < k )
        sum += x[j];
    else
        sum -= x[j];

so, if k is, say, small, -= would get called more often (duuuh). 因此,如果k很小,则-=会更频繁地被调用(duuuh)。 I tried with k = 2 which would give a higher proportion of -= called, and with k = 5 , which should yield about the same number of -= and += . 我尝试了使用k = 2 ,这会给-=更高的比例,而使用k = 5 ,它应该会产生大约相同数量的-=+=

The punchline: calling -= is about twice as faster than calling += . 重点是:调用-=大约是调用+=两倍。 Why would it be more efficient in this case? 为什么在这种情况下会更有效?

I'm gonna jump in before Mysticial gets a hold of this and guess: branch prediction . 在Mysticial掌握这一点之前,我要跳进去猜测: 分支预测

So, it's not the -= vs += . 因此,它不是-= vs +=

The condition x[j] < k can be better predicted when it's almost always true or false than it can be when there's about the same number of numbers for which it can evaluate to either. 当条件x[j] < k几乎总是为true或为false ,可以比条件x[j] < k时要更好。

For k = 2 , one in 10 will evaluate to false . 对于k = 2 ,十分之一将得出false

For k = 5 , they'll be about the same and distributed randomly, so harder to predict. 对于k = 5 ,它们将大致相同并随机分布,因此很难预测。

EDIT: See http://ideone.com/1PYMl - all extra stuff is there to prevent unused code optimization (the cout s). 编辑:请参阅http://ideone.com/1PYMl-所有其他内容均在其中以防止未使用的代码优化( cout )。

tl;dr: Results for varying k : tl; dr: k的变化结果:

k: 1 Time: 280
k: 2 Time: 360
k: 3 Time: 440
k: 4 Time: 520
k: 5 Time: 550
k: 6 Time: 510
k: 7 Time: 450
k: 8 Time: 360
k: 9 Time: 260

as you can see, the closer k gets to a chaotically varying condition, the program takes more. 如您所见, k越接近混乱变化的条件,程序花费的时间就越多。 Towards the ends, it takes about half the time. 到最后,大约需要一半的时间。

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

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