6

Full disclosure - I was inspired by Is x += a quicker than x = x + a?

That aside, I decided to test += 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). 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 +=.

The punchline: calling -= is about twice as faster than calling +=. Why would it be more efficient in this case?

Community
  • 1
  • 1
AMCoder
  • 773
  • 1
  • 6
  • 15

1 Answers1

15

I'm gonna jump in before Mysticial gets a hold of this and guess: branch prediction.

So, it's not the -= 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.

For k = 2, one in 10 will evaluate to false.

For k = 5, they'll be about the same and distributed randomly, so harder to predict.

EDIT: See http://ideone.com/1PYMl - all extra stuff is there to prevent unused code optimization (the couts).

tl;dr: Results for varying 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. Towards the ends, it takes about half the time.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 4
    so you predict it is about branch prediction – Roman R. Sep 18 '12 at 18:15
  • I was about to say the exact same thing. Also, to answer the main question at hand, on almost all architectures ever, the add and sub instructions _should_ take basically the same time. – slugonamission Sep 18 '12 at 18:15