我在 Windows 和 Linux 上的不同编译器上对数组、向量、boost::array 进行基准测试。我遇到了以下奇怪的事情。
我在 Linux 3.7.0.7 上有 gcc 4.7.2,带有标志:
g++ -O3 -g -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
而这段代码:
const int arrLength = 5;
int a[arrLength];
for (int i = 0; i < arrLength; i++) {
a[i] = i * 5;
}
srand(time(0)); // randomise at run time so it cannot be precomputed by the compiler
int numbers[10];
for (auto &i : numbers)
i = rand();
clock_t c;
c = clock();
for (int i = 0; i < 100000000; i++) {
for (int j = 0; j < arrLength; j++)
a[j] += numbers[j%10];
}
// write it out so the compiler doesn't omit the whole operation if the values in the array are not being used
for (int x : a)
cout << x;
cout << endl;
cout << (float) (clock() - c) << endl;
它实际上在 0 秒内运行......这怎么会发生?