Hi, I am trying to analyze the difference in performance from using vector vs using array in C++ with the following simple program:
array
-------
int main(){
static const int SIZE = 10000;
int arr[SIZE];
int i,j;
arr[SIZE-1] = 0; //prevent paging effects
for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i
} //main
vector
-------
#include <vector>
using std::vector;
int main(){
static const int SIZE = 10000;
vector<int> arr( SIZE );
int i,j;
arr[SIZE-1] = 0; //prevent paging effects
for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i
} //main
I ran the program and time it using 'time' on UNIX, and getting the results that array performs better than vector, with array it executes in 25.0u while with vector it takes 145.0u
I am guessing this is because vector does a dynamic memory allocation, but I am not so sure, could someone please elaborate on this one ?
Another question, the same program above is compiled using compiler optimization flag -O2, now running the program with 3 different values of the outer loop (50000, 500000, 5000000), both vectors and array keep giving me the same timing, why is this so ?
Thank you so much =)
array
-------
int main(){
static const int SIZE = 10000;
int arr[SIZE];
int i,j;
arr[SIZE-1] = 0; //prevent paging effects
for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i
} //main
vector
-------
#include <vector>
using std::vector;
int main(){
static const int SIZE = 10000;
vector<int> arr( SIZE );
int i,j;
arr[SIZE-1] = 0; //prevent paging effects
for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i
} //main
I ran the program and time it using 'time' on UNIX, and getting the results that array performs better than vector, with array it executes in 25.0u while with vector it takes 145.0u
I am guessing this is because vector does a dynamic memory allocation, but I am not so sure, could someone please elaborate on this one ?
Another question, the same program above is compiled using compiler optimization flag -O2, now running the program with 3 different values of the outer loop (50000, 500000, 5000000), both vectors and array keep giving me the same timing, why is this so ?
Thank you so much =)