为什么排序后的数组比没有排序过的数组运行快?
2017-07-03 18:01
169 查看
stackoverflow的原文地址:why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array
在上面这段代码中,如没有std:sort(data,data+arraySize);运行11.54秒,如果有则仅仅运行1.93秒。题者为了知道是不是语言或者编译器问题,也贴出了java的代码。
不想排序可以使用下面这段代码替换上面那段代码。
问题:
在stackoverflow有人问道:为什么排序后的数组比没有排序过的数组运行快?#include <algorithm> #include <ctime> #include <iostream> int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = 0; c < arraySize; ++c) data[c] = std::rand() % 256; // !!! With this, the next loop runs faster std::sort(data, data + arraySize); // Test clock_t start = clock(); long long sum = 0; for (unsigned i = 0; i < 100000; ++i) { // Primary loop for (unsigned c = 0; c < arraySize; ++c) { if (data[c] >= 128) sum += data[c]; } } double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC; std::cout << elapsedTime << std::endl; std::cout << "sum = " << sum << std::endl; }
在上面这段代码中,如没有std:sort(data,data+arraySize);运行11.54秒,如果有则仅仅运行1.93秒。题者为了知道是不是语言或者编译器问题,也贴出了java的代码。
答案:
原因是分支预测器Branch_predictor在排好序的数组里能更好地预测走if-else的哪一个分支。if (data[c] >= 128) sum += data[c];
不想排序可以使用下面这段代码替换上面那段代码。
int t = (data[c] - 128) >> 31; sum += ~t & data[c];
相关文章推荐
- 足以应付一切的水仙花数,字母交叉问题,数组排序去重复,今天get到一点点,首先一道题莫名其妙地改对了然后明白了自己思路是对的但是不会写代码 还是什么用都没有
- 给定一个未排序的整数数组,找到第一个缺失的正整数 您的算法应在O(n)时间运行,并使用恒定空间。
- 给定一个没有重复的已排序整数数组,返回其范围的摘要。
- 探究数组排序提升Python程序的循环的运行效率的原因
- Android为什么没有ios运行快
- 在用lr运行场景以后,为什么没有事务响应时间的图谱呢?
- 怎样编写一个程序,把一个有序整数数组放到二叉树中? 编写实现链表排序的一种算法。说明为什么你会选择用这样的方法?
- java运行长度10000的数组堆栈溢出,c++和Delphi都没有
- 对字符指针使用 scanf,运行时出错是为什么.(对字符数组使用scanf运行不出错)
- sort函数的用法(C++排序库函数的调用) 对数组进行排序,在c++中有库函数帮我们实现,这们就不需要我们自己来编程进行排序了。 (一)为什么要用c++标准库里的排序函数 Sort()函数是c+
- 为什么处理已排序数组比处理未排序数组更快?
- 删除排序数组中的重复数字 II 查看运行结果
- 为什么没有三维指针的疑问以及多维数组的用处
- JAVA为什么没有C/C++运行速度快
- asp.net 搭配 mysql 运行 的时候 @ 和 ? 的问题,Connector Net 最新版本,1.0版本和6.5.4版本的区别,为什么发布的时候没有包含MySql.Data.dll?
- eclipse.exe启动的时候,为什么需要指定jre?或者说,如果没有jre,为什么eclipse.exe就运行不起来,或者报错?
- C语言中,为什么没有把long转化成字符数组的函数?
- 给定按升序排序的整数数组,找到给定目标值的起始和终止位置。 您的算法的运行时复杂度必须是O(log n)的顺序。
- 搜索旋转排序数组 查看运行结果 ——LintCode
- 初见Three20【为什么Three20的Samples运行后没有反应?】