Last active
December 25, 2020 02:37
-
-
Save TheMatt2/1de1afdace157e45826d8b9ad35b80cf to your computer and use it in GitHub Desktop.
Example to show the speed difference of using an iterator across an array, versus using std::begin() iteration. Source: https://softwareengineering.stackexchange.com/questions/386614/c-iterator-why-is-there-no-iterator-base-class-all-iterators-inherit-from
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Iterator Example | |
* Modified to support clang compiler | |
* Compiler and Run: | |
* $ clang++ -Wall -Ofast -std=c++11 iterator_test.cpp && ./a.out | |
* y | |
* y | |
* time1: 143ns | |
* time2: 168ns | |
* https://softwareengineering.stackexchange.com/questions/386614/c-iterator-why-is-there-no-iterator-base-class-all-iterators-inherit-from | |
*/ | |
#include <chrono> | |
#include <iostream> | |
#include <algorithm> | |
template <class T> | |
class iterator_base { | |
public: | |
virtual T &operator*() = 0; | |
virtual iterator_base &operator++() = 0; | |
virtual bool operator==(iterator_base const &other) { return pos == other.pos; } | |
virtual bool operator!=(iterator_base const &other) { return pos != other.pos; } | |
iterator_base(T *pos) : pos(pos) {} | |
protected: | |
T *pos; | |
}; | |
template <class T> | |
class array_iterator : public iterator_base<T> { | |
using iterator_base<T>::pos; | |
public: | |
virtual T &operator*() override { return *pos; } | |
virtual array_iterator &operator++() override { ++pos; return *this; } | |
array_iterator(T *pos) : iterator_base<T>(pos) {} | |
}; | |
int main() { | |
char input[] = "asdfasdfasdfasdfasdfasdfasdfadsfasdqwerqwerqwerqrwertytyuiyuoiiuoThis is a stringy to search for something"; | |
using namespace std::chrono; | |
auto start1 = high_resolution_clock::now(); | |
auto pos = std::find(std::begin(input), std::end(input), 'g'); | |
auto stop1 = high_resolution_clock::now(); | |
std::cout << *++pos << "\n"; | |
auto start2 = high_resolution_clock::now(); | |
auto pos2 = std::find(array_iterator<char>(input), array_iterator<char>(input+sizeof(input)), 'g'); | |
auto stop2 = high_resolution_clock::now(); | |
std::cout << *++pos2 << "\n"; | |
std::cout << "time1: " << duration_cast<nanoseconds>(stop1 - start1).count() << "ns\n"; | |
std::cout << "time2: " << duration_cast<nanoseconds>(stop2 - start2).count() << "ns\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment