Results:
Vector time: 7051
Array time: 18944
I used MSVC release mode for this, compiled as 32 bit.
Before this test I was looking at the GCC source code for vector and was surprised because I thought operator[]
checked for array-out-of-bounds, but it doesn't. However, I was not expecting the vector to be so fast?!
Complete code:
#include <iostream>
#include <vector>
int main(){
const int size = 10000;
unsigned long long my_array[size];
std::vector<unsigned long long> my_vec;
my_vec.resize(size);
//Populate containers
for(int i=0; i<size; i++){
my_vec[i] = i;
my_array[i] = i;
}
//Initialise test variables
unsigned long long sum = 0;
unsigned long long time = 0;
unsigned long long start = 0;
unsigned long long finish = 0;
//Time the vector
start = __rdtsc();
for(int i=0; i<size; i++){
sum += my_vec[i];
}
finish = __rdtsc();
time = finish - start;
std::cout << "Vector time: " << time << " " << sum << std::endl;
sum = 0;
//Time the array
start = __rdtsc();
for(int i=0; i<size; i++){
sum += my_array[i];
}
finish = __rdtsc();
time = finish - start;
std::cout << "Array time: " << time << " " << sum << std::endl;
int t = 8;
std::cin >> t;
return 0;
}