问题描述
我编写了一个简单的代码来比较对两个数组(大小相同)的元素进行操作所花费的时间,一个数组由C ++数组类定义,另一个数组由纯C样式数组定义。我使用的代码是
#include <iostream>
#include <array>
#include <chrono>
using namespace std;
const int size = 1E8;
const int limit = 1E2;
array<float,size> A;
float B[size];
int main () {
using namespace std::chrono;
//-------------------------------------------------------------------------------//
auto start = steady_clock::Now();
for (int i = 0; i < limit; i++)
for (int j = 0; j < size; j++)
A.at(j) *= 1.;
auto end = steady_clock::Now();
auto span = duration_cast<seconds> (end - start).count();
cout << "Time taken for array A is: " << span << " sec" << endl;
//-------------------------------------------------------------------------------//
start = steady_clock::Now();
for (int i = 0; i < limit; i++)
for (int j = 0; j < size; j++)
B[j] *= 1.;
end = steady_clock::Now();
span = duration_cast<seconds> (end - start).count();
cout << "Time taken for array B is: " << span << " sec" << endl;
//-------------------------------------------------------------------------------//
return 0;
}
我编译并运行的
g++ array.cxx
./a.out
我得到的输出如下
Time taken for array A is: 52 sec
Time taken for array B is: 22 sec
为什么C ++数组类需要花费更长的时间进行操作?
解决方法
std::array::at
成员函数进行边界检查,因此当然会有一些额外的开销。如果您想进行更公平的比较,请使用std::array::operator[]
,就像普通数组一样。