0

我刚刚编写了一个小型 C++ 程序,只是为了了解向量如何与内存一起工作以及在运行时发生了什么。

有我的代码:

#include <iostream>
#include <cstdio>
#include <ctime>
#include <vector>

int main(){

    clock_t start, end;

    int x;

    std::vector<int> a(5, 100);

    start = clock();

    for(int i = 0 ; i <= 900000000 ; i++){
        x = a[0];
        x = a[1];
        x = a[2];
        x = a[3];
        x = a[4];
    }

    end = clock();

    clock_t duration = end - start;

    double durationPerSec = duration / (double)CLOCKS_PER_SEC;

    std::cout << "Run-time : " << durationPerSec << std::endl;

    return 0;
}

我得到了这个输出:

运行时间:18.7843

当我通过用动态数组替换向量来编写相同的代码时,运行时持续时间更容易接受:

运行时间:2.9526

我知道这段代码很愚蠢,但我想知道为什么当我使用向量时运行时间这么长?那是因为我以错误的方式使用它还是仅仅因为有些东西我不明白?

感谢回复。

4

2 回答 2

1

我运行它g++ -O0 a.cc并得到

    Run-time : 18.99

但是如果我使用g++ -O2 a.cc

    Run-time : 0

为了更主动,我运行第二个time ./a.out

time ./a.out
Run-time : 0

real    0m0.009s
user    0m0.002s
sys     0m0.002s

我将循环更改为

for(int i = 0 ; i <= 900000000 ; i++){
    a[0] = i ;
    a[1] = i + a[0];
    a[2] =  a[1] + a[2];
    a[3] = i + a[1] + a[2];
    a[4] = i + a[1] + a[2] + a[3];
    x = a[0];
    x = a[1];
    x = a[2];
    x = a[3];
    x = a[4];
}

然后的结果g++ -O2

time ./a.out
Run-time : 1.81

real    0m1.817s
user    0m1.811s
sys     0m0.001s
于 2013-09-27T14:44:46.610 回答
0

您应该在启用优化的情况下进行测量。

operator[]是成员函数。当您使用 访问元素时[0],它实际上是通过一个函数,因此尽管符号相同,但仍有更多指令要执行。在调试中,会有可测量的开销。在发布时,它通常是无法测量的。

于 2013-09-27T14:42:18.603 回答