这是一段看似非常特殊的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) 找到最多两个数字.您不应该使用if-else或任何其他比较运算符.我在网上公告板上发现了这个问题,所以我想我应该在StackOverflow中询问
示例输入:5,10输出:10
我找到了这个解决方案,有人可以帮我理解这些代码行
int getMax(int a, int b) {
int c = a - b;
int k = (c >> 31) & 0x1;
int max = a - k * c;
return max;
}
Run Code Online (Sandbox Code Playgroud) 自从我开始编程以来,我已经在每个地方阅读,以避免不惜一切代价浪费分支机构.
这很好,虽然没有一篇文章解释了为什么我应该这样做.CPU解码分支指令并决定跳转时到底发生了什么?什么是"东西"使它比其他指令(如添加)慢?
language-agnostic architecture compiler-construction cpu optimization
optimization ×2
algorithm ×1
architecture ×1
c ×1
c++ ×1
cpu ×1
java ×1
math ×1
max ×1
performance ×1