Skip to content

Instantly share code, notes, and snippets.

@karimnaaji
Last active September 8, 2016 21:40
Show Gist options
  • Save karimnaaji/a4841ecbd359492be293a000c9bf874d to your computer and use it in GitHub Desktop.
Save karimnaaji/a4841ecbd359492be293a000c9bf874d to your computer and use it in GitHub Desktop.
reserve_vs_resize.cpp
#include <time.h>
#include <stdio.h>
#include <vector>
struct A {
int mem[100];
};
int n = 1000000;
int main(int argc, char** argv) {
std::vector<A> a;
clock_t start, end;
{
a.reserve(n);
start = clock();
for (int i = 0; i < n; i++) {
a.push_back({});
}
end = clock();
printf("b.size()=%lu\n", a.size());
printf("reserve only -- %f ms\n", (float)(end - start) / CLOCKS_PER_SEC * 1000);
}
std::vector<A> b;
{
start = clock();
for (int i = 0; i < n; i++) {
b.resize(b.size()+1);
}
end = clock();
printf("b.size()=%lu\n", b.size());
printf("resize only -- %f ms\n", (float)(end - start) / CLOCKS_PER_SEC * 1000);
}
{
b.clear();
printf("b.size()=%lu\n", b.size());
start = clock();
for (int i = 0; i < n; i++) {
b.resize(b.size()+1);
}
end = clock();
printf("b.size()=%lu\n", b.size());
printf("resize after clear -- %f ms\n", (float)(end - start) / CLOCKS_PER_SEC * 1000);
}
{
b.clear();
b.reserve(n);
printf("b.size()=%lu\n", b.size());
start = clock();
for (int i = 0; i < n; i++) {
b.emplace_back();
}
end = clock();
printf("b.size()=%lu\n", b.size());
printf("resize after clear -- %f ms\n", (float)(end - start) / CLOCKS_PER_SEC * 1000);
}
return 0;
}
/*
~/Desktop/cpp_tests
▶ g++ reserve_vs_resize.cpp -std=c++14
~/Desktop/cpp_tests
▶ ./a.out
b.size()=1000000
reserve only -- 216.867004 ms
b.size()=1000000
resize only -- 593.352966 ms
b.size()=0
b.size()=1000000
resize after clear -- 70.511002 ms
b.size()=0
b.size()=1000000
resize after clear -- 45.888000 ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment