【发布时间】:2020-11-25 22:09:45
【问题描述】:
考虑下面的代码。
#include <iostream>
#include <random>
#include <chrono>
#include <memory>
const int N = 1 << 28;
int main()
{
const int seed = 0;
std::mt19937 gen;
std::uniform_real_distribution<double> dis;
std::normal_distribution<double> normal;
std::unique_ptr<bool[]> array = std::unique_ptr<bool[]>(new bool[N]);
for (int i = 0; i < N; i++)
{
if (dis(gen) > 0.5)
array[i] = true;
else
array[i] = false;
}
int sum = 0;
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++)
{
if (array[i])
sum++;
}
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " microsecond" << std::endl;
std::cout << sum << std::endl;
sum = 0;
t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++)
{
sum+=array[i];
}
t2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " microsecond" << std::endl;
std::cout << sum << std::endl;
}
如果我用std::cout << sum << std::endl; 注释行,则执行时间将显示为零(或足够接近)。我已经在不同的编译器上检查过它,包括带有 O3 编译标志的 icpc、icl (v19.1.2) 和 g++ (v9.2)。
这是乱序(动态)执行的例子吗?
【问题讨论】:
-
如果你注释掉这些行,优化器可能会让你的程序什么都不做,因为这不会有任何明显的副作用(除了执行时间)。
标签: c++ g++ icc dynamic-execution