Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <array>
- #include <vector>
- #include <utility>
- #include <chrono>
- #include <algorithm>
- #include <random>
- #include <cstdio>
- #ifndef ARRAY_SIZE
- # define ARRAY_SIZE 64
- #endif
- #ifndef LOOP_SIZE
- # define LOOP_SIZE 64
- #endif
- namespace {
- typedef std::chrono::high_resolution_clock clock;
- constexpr std::size_t array_n = ARRAY_SIZE;
- constexpr std::size_t loop_n = LOOP_SIZE;
- template<class Container>
- void init_container(Container& c)
- {
- for(std::size_t i = 0; i < c.size(); ++i)
- c[i] = i;
- }
- bool do_stack_alloc(int x)
- {
- std::array<int, array_n> stacked;
- init_container(stacked);
- return std::binary_search(stacked.begin(), stacked.end(), x);
- }
- struct DoHeapAlloc
- {
- std::vector<int> heaped;
- DoHeapAlloc():
- heaped(array_n)
- {
- init_container(heaped);
- }
- DoHeapAlloc(const DoHeapAlloc&) = delete;
- DoHeapAlloc(DoHeapAlloc&&) = default;
- bool operator()(int x) const
- {
- return std::binary_search(heaped.begin(), heaped.end(), x);
- }
- };
- template<class Strategy>
- bool test(const std::array<int, loop_n>& data, Strategy&& strategy)
- {
- bool res = false;
- for(std::size_t i = 0; i < loop_n; ++i)
- res ^= strategy(data[i]);
- return res;
- }
- template<class Strategy>
- std::pair<clock::duration, bool> time(const std::array<int, loop_n>& data,
- Strategy&& strategy)
- {
- clock::time_point t = clock::now();
- bool val = test(data, strategy);
- clock::duration dt = clock::now() - t;
- return std::make_pair(dt, val);
- }
- void make_test_data(std::array<int, loop_n>& data)
- {
- std::default_random_engine generator;
- std::uniform_int_distribution<int> distribution(0, 2 * array_n);
- for(std::size_t i = 0; i < data.size(); ++i)
- data[i] = distribution(generator);
- }
- template<class Strategy1, class Strategy2>
- void compare(Strategy1&& s1, Strategy2&& s2, const char* s1_name,
- const char* s2_name)
- {
- std::array<int, loop_n> data;
- make_test_data(data);
- std::array<std::pair<clock::duration, bool>, 4> out;
- out[0] = time(data, s1);
- out[1] = time(data, s2);
- out[2] = time(data, s1);
- out[3] = time(data, s2);
- if(out[0].second != out[1].second)
- std::printf("Strategies not equivalent\n");
- else if(out[0].first == out[1].first)
- std::printf("Cannot distinguish strategies\n");
- else if((out[0].first < out[1].first) != (out[2].first < out[3].first))
- std::printf("Performance depends on execution order\n");
- else
- std::printf("%s is faster\n", out[0].first < out[1].first ?
- s1_name : s2_name);
- }
- }
- int main()
- {
- compare(do_stack_alloc, DoHeapAlloc(), "stack allocation", "heap allocation");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment