Skip to content

Instantly share code, notes, and snippets.

@elvinio
Created January 15, 2016 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvinio/d0112785fbb69b80cb0f to your computer and use it in GitHub Desktop.
Save elvinio/d0112785fbb69b80cb0f to your computer and use it in GitHub Desktop.
Compare the memory allocation performance of vector vs array in C++
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <sys/time.h>
class Widget{
public:
int id;
Widget(){
// std::cout << "Test\n";
}
Widget& operator=(Widget other){
std::swap(id, other.id);
// std::cout << "copy assignment "<< id <<"\n";
return *this;
}
Widget(int i){
id = i;
//std::cout << "Start " << id << "\n";
}
Widget(const Widget &other){
id = other.id;
//std::cout <<"copy construct " <<id<<"\n";
}
~Widget(){
// std::cout << "Kill " << id << "\n";
}
};
int main()
{
timeval t1;
gettimeofday(&t1, nullptr);
/*Widget t(100);
Widget a = t;
std::cout << "end\n";*/
/*
std::vector<Widget> x(1000000);
for(int i = 0; i< 1000000; i++){
//x.push_back(Widget(i));
x[i] = Widget(i);
// std::cout << "pushed\n";
}
*/
Widget *w = new Widget[1000000];
for(int i = 0; i< 1000000; i++){
w[i] = Widget(i);
}
timeval t2;
gettimeofday(&t2, nullptr);
std::cout << t2.tv_sec - t1.tv_sec << " " << t2.tv_usec - t1.tv_usec <<"\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment