Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <boost/cstdint.hpp>
- #include <boost/cstdlib.hpp>
- template <typename Function>
- auto measure(const std::string& title, Function&& function)
- {
- auto buffer {
- std::chrono::duration_cast<std::chrono::nanoseconds>(
- std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::now()
- ).count()
- };
- for (std::size_t count {0}; count < 1000; ++count)
- {
- const auto begin {std::chrono::high_resolution_clock::now()};
- function();
- const auto end {std::chrono::high_resolution_clock::now()};
- buffer += std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();
- std::cout << count << "\r" << std::flush;
- }
- std::cout << title << ":\n " << buffer / 1000 << " nanosec\n\n";
- }
- int main(int argc, char** argv)
- {
- std::vector<int> vector {};
- vector.resize(0xFFFFF);
- std::cout << "[debug] vector size: " << vector.size() << "\n\n";
- measure("index access", [&]() {
- for (std::size_t index {0}; index < vector.size(); ++index)
- {
- vector[index] += 42;
- }
- });
- measure("index access (size saved)", [&]() {
- const auto size {vector.size()};
- for (std::size_t index {0}; index < size; ++index)
- {
- vector[index] += 42;
- }
- });
- measure("pointer", [&]() {
- for (auto pointer {vector.data()}; pointer != &vector.back(); ++pointer)
- {
- *pointer += 42;
- }
- });
- measure("pointer (end saved)", [&]() {
- const auto end {&vector.back()};
- for (auto pointer {vector.data()}; pointer != end; ++pointer)
- {
- *pointer += 42;
- }
- });
- measure("iterator", [&]() {
- for (auto iter {std::begin(vector)}; iter != std::end(vector); ++iter)
- {
- *iter += 42;
- }
- });
- measure("iterator (end saved)", [&]() {
- const auto end {std::end(vector)};
- for (auto iter {std::begin(vector)}; iter != end; ++iter)
- {
- *iter += 42;
- }
- });
- measure("range-based for", [&]() {
- for (auto&& each : vector)
- {
- each += 42;
- }
- });
- return boost::exit_success;
- }
Add Comment
Please, Sign In to add comment