简体   繁体   English

C ++向量内存分配和运行时?

[英]C++ Vector memory allocation & run-time?

I've just written a tiny C++ program just to understand how vectors work with memory and what's happen during run-time. 我刚刚编写了一个小型C ++程序,目的是了解向量如何与内存一起使用以及在运行时发生了什么。

There is my code : 有我的代码:

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

And i got this output : 我得到了这个输出:

Run-time : 18.7843 运行时:18.7843

When i write the same code by replacing the vector by a dynamic array the run-time duration is more acceptable : 当我通过用动态数组替换向量来编写相同的代码时,运行时持续时间更可接受:

Run-time : 2.9526 运行时:2.9526

I know this code is quite stupid but i wonder why run-time is so long when i use the vector ? 我知道这段代码很愚蠢,但我想知道为什么使用向量时运行时间这么长? Is that because i use it in the wrong way or just because there's something that i don't understand ? 是因为我以错误的方式使用它,还是仅仅因为某些我不理解的东西?

Thanks for replying. 感谢回复。

I run it with g++ -O0 a.cc and get 我用g++ -O0 a.cc运行它并得到

    Run-time : 18.99

But if I use g++ -O2 a.cc 但是如果我使用g++ -O2 a.cc

    Run-time : 0

to be more actuate , I run the second with time ./a.out 为了更加time ./a.out ,我带time ./a.out跑第二秒。

time ./a.out
Run-time : 0

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

I changed the loop to 我将循环更改为

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

Then the result of g++ -O2 is 那么g++ -O2的结果是

time ./a.out
Run-time : 1.81

real    0m1.817s
user    0m1.811s
sys     0m0.001s

You should measure with optimizations enabled. 您应该在启用优化的情况下进行测量。

operator[] is a member function. operator[]是成员函数。 When you access elements using [0] , it actually goes through a function, so there are more instructions to execute, despite identical notation. 当您使用[0]访问元素时,它实际上会通过一个函数,因此尽管符号相同,但仍有更多指令要执行。 In debug, there will be measurable overhead. 在调试中,将有可衡量的开销。 In release, it is usually unmeasurable. 在发布中,它通常无法测量。

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

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