在下面的代码中,我动态分配了两个int数组,并且只初始化其中一个。
为什么将值分配给初始化变量比将其分配给未初始化变量更快? (约0.4纳秒,约4 ns,使用带有-O3标志的g ++ 7.4.0编译,n = 10000)
#include <chrono>
#include <iostream>
#define NOW std::chrono::high_resolution_clock::now
#define DURATION_CAST(x) \
std::chrono::duration_cast<std::chrono::nanoseconds>(x).count()
int main(int argc, char* argv[])
{
int n = atoi(argv[1]);
srand(time(nullptr));
int* x = new int[n];
int* y = new int[n];
for (int i = 0; i < n; ++i)
{
x[i] = rand() / (RAND_MAX / 2);
}
auto t0 = NOW();
for (int i = 0; i < n; ++i)
x[i] = 1;
auto t1 = NOW();
for (int i = 0; i < n; ++i)
y[i] = 1;
auto t2 = NOW();
double dt1 = DURATION_CAST(t1 - t0);
double dt2 = DURATION_CAST(t2 - t1);
std::cout << "Average time: " << dt1 / n << " ns" << std::endl;
std::cout << "Average time: " << dt2 / n << " ns" << std::endl;
delete[] x;
delete[] y;
return 0;
}
Here's a version with additional print statements,以防编译器优化重要部分。