Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) TestSpeedIndexingVersusIterators

 

A simple benchmark that tests the speed of incrementing each 2D-vector's elements. It compares the speed of doing so using indexing versus using iterators.

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppTestSpeedIndexingVersusIterators.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -std=c++11
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <iostream>
#include <vector>
#include <boost/timer.hpp>

///From http://www.richelbilderbeek.nl/CppTestSpeedIndexingVersusIterators.htm
int main()
{
  const int size = 5000;
  const int nRepeat = 100;
  std::vector<std::vector<int> > v(size,std::vector<int>(size));

  double tIndexing = 0.0;
  //Add nRepeat times 1 to each element using indexing
  {
    boost::timer t;
    for (int i=0; i!=nRepeat; ++i)
    {
      for (int y=0; y!=size; ++y)
      {
        for (int x=0; x!=size; ++x)
        {
          ++v[y][x];
        }
      }
    }
    tIndexing = t.elapsed();
  }

  double tIterator = 0.0;
  //Add nRepeat times 1 to each element using iterators
  {
    boost::timer t;
    for (int i=0; i!=nRepeat; ++i)
    {
      const std::vector<std::vector<int> >::iterator rowIterEnd = v.end();
      for (std::vector<std::vector<int> >::iterator rowIter = v.begin();
        rowIter!=rowIterEnd;
        ++rowIter)
      {
        const std::vector<int>::iterator colIterEnd = (*rowIter).end();
        for (std::vector<int>::iterator colIter = (*rowIter).begin();
          colIter!=colIterEnd;
          ++colIter)
        {
          ++(*colIter);
        }
      }

    }
    tIterator = t.elapsed();
  }

  std::cout << "Time indexing: " << tIndexing
    << "\tTime iterator: " << tIterator << std::endl;
  std::cin.get();
}

 

 

 

 

 

Results

 

On a laptop (built in around 2011) with Lubuntu:

 

Time indexing: 2.88 Time iterator: 2.51

 

On the same laptop (built in around 2011) with Lubuntu using Wine:

 

Time indexing: 2.92 Time iterator: 2.58

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml