Skip to content

Instantly share code, notes, and snippets.

@harry830622
Created March 15, 2017 09:22
Show Gist options
  • Save harry830622/401711effbb00e46c32ed66956b7422b to your computer and use it in GitHub Desktop.
Save harry830622/401711effbb00e46c32ed66956b7422b to your computer and use it in GitHub Desktop.
Small experiments
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
// Assumption: Initializing a vector with size before assignments runs faster
// then filling it by "push_back"s.
int main() {
const int num_int = 100000000;
auto previous = clock();
vector<int> v1;
for (int i = 0; i < num_int; ++i) {
v1.push_back(i);
}
cout << "Without initialization: "
<< (clock() - previous) / (double)CLOCKS_PER_SEC << "s" << endl;
previous = clock();
vector<int> v2(num_int);
for (int i = 0; i < num_int; ++i) {
v2[i] = i;
}
cout << "With initialization: "
<< (clock() - previous) / (double)CLOCKS_PER_SEC << "s" << endl;
return 0;
}
// Result: It shows that the larger the vector is, the bigger the speed
// difference is. When "num_int" equals to 100 millions, it achieves 2x speedup
// on my computer.
// Conclusion: Initialize a vector using "Vector(size_t n)" when you know the
// size of the vector beforehand and the size is very large.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment