FlorentinTh
FlorentinTh

Reputation: 28

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.

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

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

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.

Upvotes: 0

Views: 1558

Answers (2)

CS Pei
CS Pei

Reputation: 11047

I run it with g++ -O0 a.cc and get

    Run-time : 18.99

But if I use g++ -O2 a.cc

    Run-time : 0

to be more actuate , I run the second with 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

time ./a.out
Run-time : 1.81

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

Upvotes: 1

justin
justin

Reputation: 104698

You should measure with optimizations enabled.

operator[] is a member function. When you access elements using [0], it actually goes through a function, so there are more instructions to execute, despite identical notation. In debug, there will be measurable overhead. In release, it is usually unmeasurable.

Upvotes: 0

Related Questions