Where Preincrement is Faster than Postincrement
September 20, 2006
Just a little example that shows the time differences between post and pre-increment on STL iterators. If you understand how they work, it's exactly as expected.
/* * 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; }Compile with:
$ g++ itertest.cpp -lrtResults in:
$ ./a.out 28ms 36ms $ ./a.out 28ms 38ms $ ./a.out 28ms 37ms $ ./a.out 28ms 41ms
6 Comments