I have a question regarding the instantiation of std::vector. I compare instantiation of an std::vector and a dynamic allocation of an array of the same size. I was expecting that the instantiation of the std::vector would take a little bit longer but I have a huge difference performance.
For the array I have 53 us For the std::vector I have 4338 us
my code:
#include <chrono>
#include <vector>
#include <iostream>
int main() {
unsigned int NbItem = 1000000 ;
std::chrono::time_point<std::chrono::system_clock> start, middle ,end;
start = std::chrono::system_clock::now() ;
float * aMallocArea = (float *)calloc(sizeof(float)*NbItem,0) ;
middle = std::chrono::system_clock::now() ;
std::vector<float> aNewArea ;
middle = std::chrono::system_clock::now() ;
aNewArea.resize(NbItem) ;
//float * aMallocArea2 = new float[NbItem];
end = std::chrono::system_clock::now() ;
std::chrono::duration<double> elapsed_middle = middle-start;
std::chrono::duration<double> elapsed_end = end-middle;
std::cout << "ElapsedTime CPU = " << elapsed_middle.count()*1000000 << " (us) " << std::endl ;
std::cout << "ElapsedTime CPU = " << elapsed_end.count()*1000000 << " (us) " << std::endl ;
free(aMallocArea) ;
return 0;
}
Even if I create a vector of size 0 I have this difference. Do you know why I have such bad performance when I am instantiating a std::vector ? Do you know how to improve this (I tried to use compilation option -O3 but it does not give outstanding result).
Compilation line: g++ --std=c++11 -o test ./src/test.cpp
compilator version: g++ --version g++ (Debian 4.7.2-5) 4.7.2 Copyright (C) 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.