Skip to content

Instantly share code, notes, and snippets.

@abel0b
Created January 20, 2020 12:25
Show Gist options
  • Save abel0b/6f58faf95209045dfbcf32fce2789a7c to your computer and use it in GitHub Desktop.
Save abel0b/6f58faf95209045dfbcf32fce2789a7c to your computer and use it in GitHub Desktop.
C++ pre-increment vs post-increment
#include <vector>
#include <chrono>
#include <iostream>
using namespace std;
int main() {
int n = 1000000;
int value = 42;
vector<int> vec(n, value);
int sum = 0;
auto start = chrono::steady_clock::now();
for(auto el = vec.begin(); el != vec.end(); el++) {
sum += *el;
}
auto end = chrono::steady_clock::now();
cout << "Post-increment : "
<< chrono::duration_cast<chrono::microseconds>(end - start).count()
<< " µs" << endl;
sum = 0;
start = chrono::steady_clock::now();
for(auto el = vec.begin(); el != vec.end(); ++el) {
sum += *el;
}
end = chrono::steady_clock::now();
cout << "Pre-increment : "
<< chrono::duration_cast<chrono::microseconds>(end - start).count()
<< " µs" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment