I am comparing the times taken to populate a list of integers against a vector of integers .
Each vector & list is populated with 10 million random integers and this experiment is repeated 100 times to find the average .
To my amazement , populating a list is about 100 times quicker than populating a vector of integers . I would expect populating vector of integer to be much faster as vector are continuous in memory and insertions are much quicker .
How can populating a list be 100 times not 10 times quicker than populating a vector. I am sure I am missing some concept or idea which is causing this
This is my code used to generate the results
#include <iostream>
#include <sstream>
#include <list>
#include <vector>
#include <ctime>
#include <time.h>
using namespace std;
int main()
{
list<int> mylist;
vector<int> myvector;
srand(time(NULL));
int num;
clock_t list_start;
clock_t list_end;
clock_t list_totaltime;
for (int i=0;i<100;i++)
{
list_start = clock();
for (int i = 0 ; i < 10000000 ; i++ ) // 10 million
{
num = rand() % 10000000 ;
mylist.push_back(num);
}
list_end = clock();
list_totaltime += difftime(list_end,list_start);
mylist.clear();
}
cout << list_totaltime/CLOCKS_PER_SEC/100;
cout <<" List is done ";
cout << endl
<< endl;
clock_t vector_start;
clock_t vector_end;
clock_t vector_totaltime;
for (int i=0;i<100;i++)
{
vector_start = clock();
for (int i = 0 ; i < 10000000 ; i++ ) // 10 million times
{
num = rand() % 10000000 ;
myvector.push_back(num);
}
vector_end = clock();
vector_totaltime += difftime(vector_end,vector_start);
myvector.clear();
}
cout << vector_totaltime/CLOCKS_PER_SEC/100;
cout << " Vector is done " ;
}
Can someone explain to me why this is happening ???