Click here to Skip to main content
15,888,025 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C++
 const unsigned arraySize = 100000;
 int data[arraySize];
 int sum = 0;

 for (unsigned c = 0; c < arraySize; ++c)
     data[c] = std::rand() % 256;

 std::sort(data, data + arraySize);

for (unsigned c = 0; c < arraySize; ++c)
{
         if (data[c] >= 128)
             sum += data[c];
 }


The above code display the result within 3.2 Sec.

Now i remove the sort method.
C++
 const unsigned arraySize = 100000;
 int data[arraySize];
 int sum = 0;

 for (unsigned c = 0; c &lt; arraySize; ++c)
     data[c] = std::rand() % 256;

for (unsigned c = 0; c < arraySize; ++c)
{
         if (data[c] >= 128)
             sum += data[c];
 }


The above code display the result within 7.2 Sec.
Posted
Updated 9-Dec-14 0:10am
v3

1 solution

Branch-prediction[^].
A guess is made whether or not to branch at the if-statement, and for the sorted one most times guessing that the previous way is the way to go will be the correct guess.
Sorting makes it easy for the branch-predictor to get it right.
 
Share this answer
 
Comments
nv3 9-Dec-14 6:41am    
What's surprising though is the additional time used for the sorting seems to take considerably less time than what is gained by branch-prediction in a single loop through the data.

And also: 7.2 sec is very slow for two trivial loops over with 100.000 iterations on any modern processor.

My suspicion: The measurement was not done correctly.
Aescleal 9-Dec-14 11:30am    
I think there's probably something a bit weird with his measurements as well. My rather naff i5 can do a partial sum of 20 million ints in about 80ms. Sorting the data takes ages but halves the time taken to do the partial sum. Even better is partioning the data into two ranges and then just summing the range you want - that takes about 4ms.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900