Why is processing a sorted array faster than an unsorted array(Stackoverflow)
What is Branch Prediction?Consider a railroad junction:
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 slow down. Is there a better way? You guess which direction the train will go!
If you guess right every time, the train will never have to stop. 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 guess right every time, the execution will never have to stop. 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 left. If it alternates, then you alternate your 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:
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:
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)
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 sacrifice readability for performance. Replace:
with:
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 of Benchmarks: Core i7 920 @ 3.5 GHz C++ - Visual Studio 2010 - x64 Release
Java - Netbeans 7.1.1 JDK 7 - x64
Observations:
A general rule of thumb is to avoid data-dependent branching in critical loops. (such as in this example) Update :
This goes to show that even mature modern compilers can vary wildly in their ability to optimize code... |
|||
| 每一次CPU运行这个条件推断时,CPU都可能跳转到循环開始处的指令。即不运行if后的指令。
使用分支预測技术。当处理已经排序的数组时。在若干次data[c]>=128都不成立时(或第一次不成立时。取决于分支预測的实现),CPU预測这个分支是始终会跳转到循环開始的指令时。这个时候CPU将保持有效的运行,不须要又一次等待到新的地址取指。相同。当data[c]>=128条件成立若干次后,CPU也能够预測这个分支是不必跳转的。那么这个时候CPU也能够保持高效运行。 |
|
Why is processing a sorted array faster than an unsorted array(Stackoverflow)的更多相关文章
- Why is processing a sorted array faster than an unsorted array?
这是我在逛 Stack Overflow 时遇见的一个高分问题:Why is processing a sorted array faster than an unsorted array?,我觉得这 ...
- find K maximum value from an unsorted array(implement min heap)
Maintain a min-heap with size = k, to collect the result. //Find K minimum values from an unsorted a ...
- 108.Convert Sorted Array to Binary Search Tree(Array; Divide-and-Conquer, dfs)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 思路 ...
- Kth Smallest Element in Unsorted Array
(referrence: GeeksforGeeks, Kth Largest Element in Array) This is a common algorithm problem appeari ...
- JavaScript,通过分析Array.prototype.push重新认识Array
在阅读ECMAScript的文档的时候,有注意到它说,数组的push方法其实不仅限于在数组中使用,专门留作通用方法.难道是说,在一些类数组的地方也可以使用?而哪些是和数组非常相像的呢,大家或许一下子就 ...
- String方法,js中Array方法,ES5新增Array方法,以及jQuery中Array方法
相关阅读:https://blog.csdn.net/u013185654/article/details/78498393 相关阅读:https://www.cnblogs.com/huangyin ...
- numpy array转置与两个array合并
我们知道,用 .T 或者 .transpose() 都可以将一个矩阵进行转置. 但是一维数组转置的时候有个坑,光transpose没有用,需要指定shape参数, 在array中,当维数>=2, ...
- [Javascript] Different ways to create an new array/object based on existing array/object
Array: 1. slice() const newAry = ary.slice() 2. concat const newAry = [].concat(ary) 3. spread oprea ...
- php xml转数组,数组转xml,array转xml,xml转array
//数组转XML function arrayToXml($arr) { $xml = "<xml>"; foreach ($arr as $key=>$val) ...
随机推荐
- Smarty的应用
smarty模板的核心是一个类,下载好的模板中有这么几个重要的文件夹 (1)libs核心文件夹(2)int.inc.php这是入口文件(3)plugins:自己写的插件文件夹(4)templates_ ...
- 【Linux】CentOS安装Jenkins
sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo sudo rpm -- ...
- 执行join_paired_ends.py报错Cannot find fastq-join
通过 conda 安装 qiime 1后,在执行join_paired_ends.py时报错: burrito.util.ApplicationNotFoundError: Cannot find f ...
- 少啰嗦!一分钟带你读懂Java的NIO和经典IO的区别
1.引言 很多初涉网络编程的程序员,在研究Java NIO(即异步IO)和经典IO(也就是常说的阻塞式IO)的API时,很快就会发现一个问题:我什么时候应该使用经典IO,什么时候应该使用NIO? 在本 ...
- Python字符的转义
参考原文 廖雪峰Python教程 字符的转义 字符串是以单引号' 或双引号" 括起来的任意文本,比如'abc',"xyz".''或""本身只是一种表示 ...
- java学习日志--char和int的相互转换
package shugen; /*ASCLL码表 * 48 数字0 * 49 1 * 50 2 * 51 3 * 52 4 * 53 5 * 54 6 * 55 7 * 56 8 * 57 9 */ ...
- 「 Luogu P1850 」 换教室
解题思路 很明显的是个期望 $dp$. 先前想到 $dp[i][j]$ 表示第决策到第 $i$ 个时间段,已经进行了 $j$ 次申请,然后就没有然后了,因为这根本就没法转移啊,你又不知道前 $i-1$ ...
- Gym - 101670B Pond Cascade(CTU Open Contest 2017 贪心,二分)
题目: The cascade of water slides has been installed in the park recently and it has to be tested. The ...
- Linux 服务器 U盘安装(避免U盘启动)以及拔除U盘后无法引导系统
一.U盘制作 首先下载两个文件: · rhel-server-6.3-i386-boot.iso 启动镜像 · rhel-server-6.3-i386-dvd. ...
- atCoder Ants on a Circle(又是蚂蚁问题。。。)
atCoder Ants on a Circle(又是蚂蚁问题...) 传送门 题意:一个圈,蚂蚁在上面以相同的速度和不同的方向走,问t秒后它们各自的位置. 解法:和经典的蚂蚁问题一致,把相撞的情况看 ...

