-O3
优化标志编译此代码,则需要2.98605秒
才能运行。如果我使用-O2
编译,那么需要1.98093秒
。我在同一台机器上,在相同的环境中多次运行此代码(5或6次),关闭所有其他软件(chrome、skype等)。gcc --version
gcc (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
所以,请您能够解释一下为什么会出现这种情况吗?我阅读了gcc
手册,发现-O3
包含了-O2
。谢谢您的帮助。
附言:添加代码
#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;
}
-mtune=native
编译 - 与之前相同的结果(没有此标志)。处理器 - Intel Core i5-2400。 - Mike MinaevO2
中添加了额外的优化,这些优化与O3
一次执行一个。O3
为我添加的额外优化标志是:-fgcse-after-reload -finline-functions -fipa-cp-clone -fpredictive-commoning -ftree-loop-distribute-patterns -ftree-vectorize -funswitch-loops
。我发现将-ftree-vectorize
作为优化标志添加到O2
中会产生负面影响。我使用的是Windows 7和mingw-gcc 4.7.2。 - halexsum
从局部变量更改为全局或静态变量,可以消除O2和O3之间的差异。问题似乎与在循环内存储和检索局部变量sum
时进行了大量堆栈操作有关。我的汇编知识太有限,无法完全理解gcc生成的代码 :) - halex