Skip to content

Instantly share code, notes, and snippets.

@giuliano0
Last active May 29, 2016 02:31
Show Gist options
  • Save giuliano0/efba44b85da963527f8561efe4b5cce4 to your computer and use it in GitHub Desktop.
Save giuliano0/efba44b85da963527f8561efe4b5cce4 to your computer and use it in GitHub Desktop.
Testing indexed loops versus iterators (compile and run with -std=c++11 -O[1-3])
#include <vector>
#include <iostream>
#include <chrono>
using namespace std;
int main() {
const size_t BIG = 200000000;
vector <int> v;
for (size_t i = 0; i < BIG; i++) {
v.push_back(i);
}
cout << "start" << endl;
int n = 0;
auto t_start = chrono::high_resolution_clock::now();
for(vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
n += *it;
}
auto t_end = chrono::high_resolution_clock::now();
cout << chrono::duration<double, milli>(t_end - t_start).count() << endl;
t_start = chrono::high_resolution_clock::now();
for(size_t i = 0; i < v.size(); ++i) {
n += v[i];
}
t_end = chrono::high_resolution_clock::now();
cout << chrono::duration<double, milli>(t_end - t_start).count() << endl;
return n != 0;
}
@giuliano0
Copy link
Author

Code heavily based on a random stackoverflow topic about the subject.

I modified the time measuring so it uses chrono instead of clock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment