Who's General Failure and why's he reading my disk?
/*
* Times the difference between using ++i and i++ on iterators in a loop.
*/
#include <iostream>
#include <vector>
#include <sys/time.h>
using namespace std;
struct timespec s;
inline void start()
{
(void)clock_gettime(CLOCK_REALTIME,&s);
}
inline void stop()
{
struct timespec now;
(void)clock_gettime(CLOCK_REALTIME,&now);
unsigned int diff = (unsigned int)((double)(now.tv_sec-s.tv_sec) * 1000.0) +
(unsigned int)((double)(now.tv_nsec-s.tv_nsec) / 1000000.0);
cout << diff << "ms" << endl;
}
int main()
{
vector<int> v;
for (unsigned int x = 0; x < 1000000;x++)
{
v.push_back(x);
}
{
start();
for (vector<int>::iterator i = v.begin(); i != v.end();++i)
{
(*i)++;
}
stop();
}
{
start();
for (vector<int>::iterator i = v.begin(); i != v.end();i++)
{
(*i)--;
}
stop();
}
return 0;
}
$ g++ itertest.cpp -lrt
$ ./a.out 28ms 36ms $ ./a.out 28ms 38ms $ ./a.out 28ms 37ms $ ./a.out 28ms 41ms