Why are processing a sorted array faster than an unsorted array (StackOverflow)

Source: Internet
Author: User

 what is branch prediction? Consider a railroad junction:image by mecanismo, via wikimedia commons .  used under the cc-by-sa 3.0 license. now for the sake of argument, suppose this is back in  The 1800s - before long distance or radio communication. You are the operator of a junction and you hear a train  coming. you have no idea which way it will go. you  stop the train to ask the captain which direction he  Wants. and then you set the switch appropriately. trains are heavy and have a lot of inertia. so they  take forever to start up and&Nbsp;slow down. Is there a better way? you guess which direction the train  will go!
If you guessed right, it continues on.
If you guessed wrong, the captain would stop, back up, and yell at your to flip the switch. Then it can restart down the other path.
If you guess right every time, the train would never has to stop.
if you guess wrong too often, the train will spend a  Lot of time stopping, backing up, and restarting. consider an if-statement: at the processor level, it is a  Branch instruction:you are a processor and you see a branch.  You have no idea which way it will go. What do  you do? you halt execution and wait until the previous  instructions are complete. then you continue down the correct  Path. modern processors are complicated and have long pipelines. so  they take forever to  "Warm up"  and  "Slow down". Is there a better way? you guess which&nbSp;direction the branch will go!
If you guessed right, you continue executing.
If you are guessed wrong, you need-to-flush the pipeline and roll back to the branch. Then you can restart down the other path.
If you guess right every time, the execution would never has to stop.
If you guess wrong too often, you spend a lot of time  stalling, rolling back, and restarting. This is branch prediction. i admit it ' S not the best analogy  since the train could just signal the direction with a  FLAG. BUT IN COMPUTERS, THE PROCESSOR DOESN ' t know which  Direction a branch will go until the last moment. so how would you strategically guess to minimize the number  Of times that the train must back up and go down the  other path? you look at the past history! if the train  goes left 99% of the time, then you guess&Nbsp;left. if it alternates, then you alternate your guesses. if  it goes one way every 3 times, you guess the same ... In other words, you try to identify a pattern and follow  it. this is more or less how branch predictors work. most applications have well-behaved branches. so modern branch  predictors will typically achieve >90% hit rates. but when  faced with unpredictable branches with no recognizable patterns,  Branch predictors are virtually useless. further reading:  "Branch predictor"  article on Wikipedia.As hinted  From above, the culprit is this if-statement:if (data[c]>=128) Sum+=data[c]; notice that the data is evenly distributed between 0 and  255. when the data is sorted, roughly the first half of  the iterations will not enter the if-statement. after that,  they will all enter the if-statement. this is very friendly to the branch predictor since the  Branch consecutively goes the same direction many times. even a simple saturating counter will correctly predict the  Branch except for the few iterations after it switches direction. quick visualization:t=branch takenn=branchnottakendata[]=0,1,2,3,4,... 126,127,128,129,130,... 250,251,252,... branch=n  n  n  n  n ... n    n    t    t    t ... T    t    t...=nnnnnnnnnnnn ... Nnnnnnnttttttttt ... TTTTTTTTTT (easy to predict) however, when the data is completely random ,  the branch predictor is rendered useless because it can ' t  Predict random data. thus there will probably be around 50% misprediction.  (No better  than random guessing) data[]=226,185,125,158,198,144,217,79,202,118,14,150,177,182,133,... Branch=t,t,n,t,t,t,t,n,t,n,n,t,t,t,n...=ttnttttntnntttn ... (completely random-hard to predict) So what can be done? If the compiler isn ' T able to optimize the branch into a  conditional move, you can try some hacks if you&nbSp;are willing to sacrifice readability for performance. Replace:if (data[c]>=128) sum+=data[c];with:intt= (data[c]-128) >>31;sum+=~t&data[c]; This eliminates the branch and replaces it with some bitwise  operations. (note that this hack is not strictly equivalent to the  Original if-statement. but in this case, it ' s valid for all  The input values ofdata[].) benchmarks: core i7 920 @ 3.5 ghzc++ - visual studio 2010  - x64 release//  branch - randomseconds=11.777//  branch -  sortedseconds=2.352//  branchless - randomseconds=2.564//  branchless  - Sortedseconds=2.587Java - Netbeans 7.1.1 JDK 7 - x64//   branch - Randomseconds=10.93293813//  Branch - Sortedseconds=5.643797077//   branchless - randomseconds=3.113581453//  branchless - sortedseconds= 3.186068823Observations:
The Branch:there is a huge difference between the sorted and unsorted data.
With the hack:there is no difference between sorted and unsorted data.
In the C + + case, the hack are actually a tad slower than with the branch when the data is sorted.
A general rule of thumb was to avoid data-dependent branching in critical loops. (such as in this example) Update:
GCC 4.6.1 With-o3 or-ftree-vectorize on x64 are able to generate a conditional move. So there was no difference between the sorted and unsorted data-both are fast.
VC + Unable to generate conditional moves for this branch even under/ox.
Intel Compiler does something miraculous. It interchanges the loops, thereby hoisting the unpredictable branch to the outer loop. So isn't only it immune the mispredictions, it's also twice as fast as whatever VC + + GCC can generate! In other words, ICC took advantage of the Test-loop to defeat the benchmark ...
If you give the Intel Compiler the branchless code, it just out-right vectorizes it ... and is just as fast as with the bra Nch (with the Loop interchange).
This goes to show the even mature modern compilers can vary wildly in their ability to optimize code ...

Each time the CPU performs this condition judgment, the CPU may jump to the instruction at the beginning of the loop, i.e., without executing the IF instruction. With the branch prediction technique, when processing an array that has already been sorted, when a number of times the data[c]>=128 is not established (or the first time it is not, depending on the implementation of the branch prediction), the CPU predicts that the branch will always jump to the start of the loop and this time the CPU remains in effect. There is no need to wait for a new address to be picked up, similarly, when the data[c]>=128 condition is set up several times, the CPU can also predict that the branch does not have to jump, then this time the CPU can also remain efficient execution.

Conversely, in the case of an unordered array, the CPU's branch predictions are largely unpredictable, essentially 50% of the probability of success, which consumes a lot of time because the CPU waits many times for the reference unit to be picked up.

Why are processing a sorted array faster than an unsorted array (StackOverflow)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.