Created
February 22, 2014 11:52
-
-
Save matthiasvegh/9152765 to your computer and use it in GitHub Desktop.
ph::find benchmark
This file contains hidden or 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
| #include <iterator> | |
| #include <chrono> | |
| #include <random> | |
| #include <cstring> | |
| #include <algorithm> | |
| #include <iostream> | |
| #include <type_traits> | |
| namespace ph { | |
| template<typename Begin, typename End, typename ValueType> | |
| Begin find(Begin begin, End end, const ValueType& value) { | |
| for(; end != begin; ++begin) { | |
| if(*begin == value) { | |
| return begin; | |
| } | |
| } | |
| return begin; | |
| } | |
| struct LazyStrIterator { | |
| template<typename Iterator> | |
| inline | |
| bool operator==(Iterator&& other) { | |
| return *std::forward<Iterator>(other) == '\0'; | |
| } | |
| template<typename Iterator> | |
| inline | |
| bool operator!=(Iterator&& other) { | |
| return ! (this->operator==(std::forward<Iterator>(other))); | |
| } | |
| }; | |
| } // namespace ph | |
| int main() { | |
| std::random_device rnd; | |
| std::mt19937 gen(rnd()); | |
| std::uniform_int_distribution<> dis('A', 'z'); | |
| char* str = new char[1024]; | |
| std::memset(str, '\0', 1024); | |
| for(auto it=str; it<str+1023; ++it) { | |
| *it = dis(gen); | |
| } | |
| // test str complete. now for testing. | |
| { | |
| auto start = std::chrono::high_resolution_clock::now(); | |
| auto endIterator = str+strlen(str); // O(n) | |
| auto pos = std::find(str, endIterator, 'a'); | |
| auto end = std::chrono::high_resolution_clock::now(); | |
| std::cout<< "std::find: " << (end - start).count() << std::endl; | |
| } | |
| { | |
| auto start = std::chrono::high_resolution_clock::now(); | |
| auto endIterator = ph::LazyStrIterator{}; | |
| auto pos = ph::find(str, endIterator, 'a'); | |
| auto end = std::chrono::high_resolution_clock::now(); | |
| std::cout<< "ph::find: " << (end - start).count() << std::endl; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment