为什么 C++ 数组类比 C 风格的数组花费更多的时间来操作?

XCS*_*CSM -2 c++ arrays time compiler-optimization

我编写了一个简单的代码来比较对两个数组(两个大小相同)的元素进行操作所花费的时间,一个由 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;
    }
Run Code Online (Sandbox Code Playgroud)

我已经编译并运行

g++ array.cxx
./a.out
Run Code Online (Sandbox Code Playgroud)

我得到的输出如下

Time taken for array A is: 52 sec
Time taken for array B is: 22 sec
Run Code Online (Sandbox Code Playgroud)

为什么 C++ 数组类需要更长的时间来操作?

Bla*_*ace 7

std::array::at成员函数做边界检查等等,当然,还有一些额外的开销。如果您想要更公平的比较,请使用std::array::operator[],就像普通数组一样。