这是一段看似非常特殊的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) 我在2009年首先注意到GCC(至少在我的项目和我的机器上)如果我优化尺寸(-Os
)而不是速度(-O2
或-O3
),则会产生明显更快的代码,我一直想知道为什么.
我设法创建(相当愚蠢)代码,显示这种令人惊讶的行为,并且足够小,无法在此处发布.
const int LOOP_BOUND = 200000000;
__attribute__((noinline))
static int add(const int& x, const int& y) {
return x + y;
}
__attribute__((noinline))
static int work(int xval, int yval) {
int sum(0);
for (int i=0; i<LOOP_BOUND; ++i) {
int x(xval+sum);
int y(yval+sum);
int z = add(x, y);
sum += z;
}
return sum;
}
int main(int , char* argv[]) {
int result = work(*argv[1], *argv[2]);
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果我用-Os
它编译它,执行这个程序需要0.38秒,如果用-O2 …
我记得假设在我的架构类中L1缓存命中是1个周期(即与寄存器访问时间相同),但在现代x86处理器上实际上是这样吗?
L1缓存命中多少个周期?它与寄存器访问相比如何?
performance x86 cpu-architecture micro-optimization cpu-cache
现代CPU的缓存访问速度是多少?Intel P4,Core2,Corei7,AMD每个处理器时钟周期内可以从内存中读取或写入多少字节?
请回答理论(ld/sd单位的宽度及其uOPs/tick的吞吐量)和实际数字(甚至是memcpy速度测试,或STREAM基准测试),如果有的话.
PS是问题,与汇编程序中的最大加载/存储指令率有关.可以有理论加载速率(所有每个Tick的指令都是最宽的负载),但是处理器只能给出部分这样的,一个实际的加载限制.
performance ×4
c++ ×2
cpu-cache ×2
caching ×1
cpu ×1
gcc ×1
java ×1
optimization ×1
x86 ×1
x86-64 ×1