Is + = faster than - =?

Full disclosure - I was inspired. Is x + = faster than x = x + a?

Aside, I decided to test += vs -= . Simple tests show that they are 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 -= proportion to the given number:

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

therefore, if k , say, small, -= will be called more often (duuuh). I tried with k = 2 , which would give a higher proportion of the called -= , and with k = 5 , which should give about the same amount -= and += .

Dotted line: a call -= about twice as fast as a call += . Why would it be more efficient in this case?

+6
source share
1 answer

I'm going to jump in before Mystical grabs onto this and guesses: branch prediction .

So this is not -= vs += .

The condition x[j] < k can be better predicted when it is almost always true or false than it can be when there is about the same number of numbers for which it can be estimated.

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

For k = 5 , they will be approximately the same and randomly distributed, so it is difficult to predict.

EDIT: see http://ideone.com/1PYMl - all that is needed to prevent unused code optimization ( cout s).

tl; dr: Results for changing 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 goes into a chaotically changing state, the program takes more. In the end, it takes about half the time.

+15
source

Source: https://habr.com/ru/post/925696/


All Articles