简体   繁体   English

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

[英]Why C++ array class is taking more time to operate on, than the C-style array?

I have written a simple code to compare the time taken to operate on the elements of two arrays (both of same size), one defined by C++ array class and the other by plain C-style array.我编写了一个简单的代码来比较对两个数组(两个大小相同)的元素进行操作所花费的时间,一个由 C++ 数组类定义,另一个由普通的 C 样式数组定义。 The code I have used is我使用的代码是

    #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;
    }

which I have compiled and run with我已经编译并运行

g++ array.cxx
./a.out

The output I get is the following我得到的输出如下

Time taken for array A is: 52 sec
Time taken for array B is: 22 sec

Why does the C++ array class takes much longer to operate on?为什么 C++ 数组类需要更长的时间来操作?

The std::array::at member function does bounds-checking so, of course, there is some extra overhead. std::array::at成员函数进行边界检查,因此当然会有一些额外的开销。 If you want a fairer comparison use std::array::operator[] , just like the plain array.如果您想要更公平的比较,请使用std::array::operator[] ,就像普通数组一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM