Skip to content

Instantly share code, notes, and snippets.

@nlguillemot
Created June 25, 2012 00:57
Show Gist options
  • Save nlguillemot/2985823 to your computer and use it in GitHub Desktop.
Save nlguillemot/2985823 to your computer and use it in GitHub Desktop.
Comparison of performance of adding elements to preallocated containers in c++11
#include <vector>
#include <list>
#include <iostream>
#include <ctime>
// FIXME: v(1000000) creates a vector of 1000000 elements. At the end of the function there are 2000000 elements. Instead, it should be constructed empty and then v.reserve(1000000) should be called just after.
void createPreallocatedMillionVector()
{
std::vector<int> v(1000000);
for (int i = 0; i < 1000000; ++i)
{
v.push_back(i);
}
}
void createMillionVector()
{
std::vector<int> v;
for (int i = 0; i < 1000000; ++i)
{
v.push_back(i);
}
}
// FIXME: This actually creates a list of 2000000 elements. Should instead use a pool allocator.
void createPreallocatedMillionList()
{
std::list<int> L(1000000, 0);
for (int i = 0; i < 1000000; ++i)
{
L.push_back(i);
}
}
void createMillionList()
{
std::list<int> L;
for (int i = 0; i < 1000000; ++i)
{
L.push_back(i);
}
}
int main()
{
clock_t startTime = clock();
createMillionVector();
clock_t postVectorTime = clock();
createPreallocatedMillionVector();
clock_t postAllocVectorTime = clock();
createMillionList();
clock_t postListTime = clock();
createPreallocatedMillionList();
clock_t postAllocListTime = clock();
std::cout << "Vector took " << (postVectorTime - startTime) / (float)CLOCKS_PER_SEC << " seconds." << std::endl;
std::cout << "Preallocated Vector took " << (postAllocVectorTime - postVectorTime) / (float)CLOCKS_PER_SEC << " seconds." << std::endl;
std::cout << "List took " << (postListTime - postAllocVectorTime) / (float)CLOCKS_PER_SEC << " seconds." << std::endl;
std::cout << "Preallocated List took " << (postAllocListTime - postListTime) / (float)CLOCKS_PER_SEC << " seconds." << std::endl;
}
Vector took 0.04 seconds.
Preallocated Vector took 0.04 seconds.
List took 0.24 seconds.
Preallocated List took 0.46 seconds.
Vector took 0.01 seconds.
Preallocated Vector took 0.02 seconds.
List took 0.13 seconds.
Preallocated List took 0.25 seconds.
Vector took 0.04 seconds.
Preallocated Vector took 0.04 seconds.
List took 0.24 seconds.
Preallocated List took 0.46 seconds.
Vector took 0.01 seconds.
Preallocated Vector took 0.02 seconds.
List took 0.13 seconds.
Preallocated List took 0.25 seconds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment