C++ Vector vs Array (Time)
- by vsha041
I have got here two programs with me, both are doing exactly the same task. They are just setting an boolean array / vector to the value true. The program using vector
takes 27 seconds to run whereas the program involving array with 5 times greater size takes less than 1 s. I would like to know the exact reason as to why there is such a major difference ? Are vectors
really that inefficient ?
Program using vectors
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main(){
const int size = 2000;
time_t start, end;
time(&start);
vector<bool> v(size);
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
v[i] = true;
}
}
time(&end);
cout<<difftime(end, start)<<" seconds."<<endl;
}
Runtime - 27 seconds
Program using Array
#include <iostream>
#include <ctime>
using namespace std;
int main(){
const int size = 10000; // 5 times more size
time_t start, end;
time(&start);
bool v[size];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
v[i] = true;
}
}
time(&end);
cout<<difftime(end, start)<<" seconds."<<endl;
}
Runtime - < 1 seconds
Platform - Visual Studio 2008
OS - Windows Vista 32 bit SP 1
Processor Intel(R) Pentium(R) Dual CPU T2370 @ 1.73GHz
Memory (RAM) 1.00 GB
Thanks
Amare