Why is processing a sorted array faster than unsorted array (Stackoverflow), stackoverflow

Source: Internet
Author: User

Why is processing a sorted array faster than unsorted array (Stackoverflow), stackoverflow

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 1800 s-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 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 will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, The train will never have 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 direction the branch will go!

  • If you guessed right, you continue executing.
  • If you 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 will never have 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 coshould 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 wocould 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 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 such patterns, branch predictors are always Ally 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 limit goes the same direction limit times. Even a simple saturating counter will correctly predict the branch limit t for the few iterations after it switches direction.

Quick visualization:

T = branch takenN = branch not takendata[] = 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 und 50% seconds. (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 are willing to sacrifle ice readability for performance.

Replace:

if (data[c] >= 128)    sum += data[c];

With:

int t = (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 valuesdata[].)

Benchmarks: Core i7 920 @ 3.5 GHz

C ++-Visual Studio 2010-x64 Release

//  Branch - Randomseconds = 11.777//  Branch - Sortedseconds = 2.352//  Branchless - Randomseconds = 2.564//  Branchless - Sortedseconds = 2.587

Java-Netbeans 7.1.1 JDK 7-x64

//  Branch - Randomseconds = 10.93293813//  Branch - Sortedseconds = 5.643797077//  Branchless - Randomseconds = 3.113581453//  Branchless - Sortedseconds = 3.186068823

Observations:

  • With 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 is actually a tad slower than with the branch when the data is sorted.

A general rule of thumb is to avoid data-dependent branching in critical loops. (such as in this example)

Update:

  • GCC 4.6.1-O3Or-ftree-vectorizeOn x64 is able to generate a conditional move. So there is no difference between the sorted and unsorted data-both are fast.

  • VC ++ 2010 is unable to generate conditional moves for this branch even under/Ox.

  • Intel Compiler 11 does something miraculous. it interchanges the two loops, thereby hoisting the unpredictable branch to the outer loop. so not only is it immune the mispredictions, it is also twice as fast as whatever VC ++ and 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 branch (with the loop interchange ).

This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...

   
Each time the CPU executes this condition, the CPU may jump to the command at the beginning of the loop, that is, the command after the if is not executed. When processing sorted Arrays Using the branch prediction technology, when data [c]> = 128 fails several times (or the first failure depends on the implementation of the branch prediction ), when the CPU predicts that this branch will always jump to the command starting from the loop, the CPU will continue to be executed effectively and you do not need to wait for the new address to get the pointer. Similarly, when the data [c]> = 128 condition is set up several times, the CPU can also predict that this branch does not have to jump, so the CPU can also be executed efficiently at this time.

On the contrary, if an unordered array is used, the branch prediction of the CPU cannot be successfully predicted to a large extent. Basically, it is 50% of the probability of successful prediction, which consumes a lot of time, because the CPU spends a lot of time waiting for the fetch unit to re-Fetch the finger.

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.