Iterating over vectors - speed difference
Hi
I am comparing the runtime of iterating through a vector using 3
different approaches -
1) Indexing -> i = 0; i < vec.size();
2) Iterator -> i = vec.begin(), i != vec.end()
3) Summing using Accumulate
Here are the runtimes on my computer. I am compiling using VC++ 2008,
Release mode build. Runtimes are pretty stable from run to run.
1) Indexing -> 1.884 s
2) Iterator -> 8.725 s
3) Accumulate -> 1.8 s
As expected, accumulate is the fastest of them all, but only by a
narrow margin. The shocker is using iterators is nearly 5 times slower
than indexing, whereas I expected the two to be nearly at par. I don't
understand why this should happen.
Is this a case specific to VC++ / Dinkumware libraries ? Or is this
expected based on the C++ standard ? Or have I made an error in my
benchmarking ?
Thanks for your responses!
-Arijit
#include <iostream>
#include <vector>
#include <numeric>
#include <ctime>
using namespace std;
int main()
{
const int maxnum = 1000000;
const int iter = 1000;
vector<int> num;
num.reserve(maxnum);
for(int i = 0; i < maxnum; ++i)
num.push_back(i);
clock_t start = clock();
long long sum = 0;
for(int i = 0; i < iter; ++i)
for(unsigned int j = 0; j < num.size(); ++j)
sum += num[j];
cout << sum << endl;
clock_t mid = clock();
sum = 0;
for(int i = 0; i < iter; ++i)
for(vector<int>::iterator j = num.begin(); j != num.end(); ++j)
sum += *j;
cout << sum << endl;
clock_t late = clock();
sum = 0;
for(int i = 0; i < iter; ++i)
sum += accumulate(num.begin(), num.end(), 0ll);
cout << sum << endl;
clock_t end = clock();
cout << endl << static_cast<double>(mid - start) / CLOCKS_PER_SEC;
cout << endl << static_cast<double>(late - mid) / CLOCKS_PER_SEC;
cout << endl << static_cast<double>(end - late) / CLOCKS_PER_SEC <<
endl << endl;
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]