这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#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) …Run Code Online (Sandbox Code Playgroud) 从优化和分支预测器的角度来看,这两个代码之间有什么区别吗?
第一:
void think_and_do(){
if(expression){
//Set_A of instructions
}
else{
//Set_B of instructions
}
}
int main(){
think_and_do();
}
Run Code Online (Sandbox Code Playgroud)
第二:
void do_A(){
//Set_A of instructions
}
void do_B(){
//Set_B of instructions
}
int main(){
if(expression){
do_A();
}
else{
do_B();
}
}
Run Code Online (Sandbox Code Playgroud)