Created
January 15, 2016 07:37
-
-
Save elvinio/d0112785fbb69b80cb0f to your computer and use it in GitHub Desktop.
Compare the memory allocation performance of vector vs array in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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