Guest User

Untitled

a guest
Oct 22nd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #include <boost/cstdint.hpp>
  4. #include <boost/cstdlib.hpp>
  5.  
  6.  
  7. template <typename Function>
  8. auto measure(const std::string& title, Function&& function)
  9. {
  10. auto buffer {
  11. std::chrono::duration_cast<std::chrono::nanoseconds>(
  12. std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::now()
  13. ).count()
  14. };
  15.  
  16. for (std::size_t count {0}; count < 1000; ++count)
  17. {
  18. const auto begin {std::chrono::high_resolution_clock::now()};
  19. function();
  20. const auto end {std::chrono::high_resolution_clock::now()};
  21.  
  22. buffer += std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();
  23. std::cout << count << "\r" << std::flush;
  24. }
  25.  
  26. std::cout << title << ":\n " << buffer / 1000 << " nanosec\n\n";
  27. }
  28.  
  29.  
  30. int main(int argc, char** argv)
  31. {
  32. std::vector<int> vector {};
  33. vector.resize(0xFFFFF);
  34.  
  35. std::cout << "[debug] vector size: " << vector.size() << "\n\n";
  36.  
  37. measure("index access", [&]() {
  38. for (std::size_t index {0}; index < vector.size(); ++index)
  39. {
  40. vector[index] += 42;
  41. }
  42. });
  43.  
  44. measure("index access (size saved)", [&]() {
  45. const auto size {vector.size()};
  46. for (std::size_t index {0}; index < size; ++index)
  47. {
  48. vector[index] += 42;
  49. }
  50. });
  51.  
  52. measure("pointer", [&]() {
  53. for (auto pointer {vector.data()}; pointer != &vector.back(); ++pointer)
  54. {
  55. *pointer += 42;
  56. }
  57. });
  58.  
  59. measure("pointer (end saved)", [&]() {
  60. const auto end {&vector.back()};
  61. for (auto pointer {vector.data()}; pointer != end; ++pointer)
  62. {
  63. *pointer += 42;
  64. }
  65. });
  66.  
  67. measure("iterator", [&]() {
  68. for (auto iter {std::begin(vector)}; iter != std::end(vector); ++iter)
  69. {
  70. *iter += 42;
  71. }
  72. });
  73.  
  74. measure("iterator (end saved)", [&]() {
  75. const auto end {std::end(vector)};
  76. for (auto iter {std::begin(vector)}; iter != end; ++iter)
  77. {
  78. *iter += 42;
  79. }
  80. });
  81.  
  82. measure("range-based for", [&]() {
  83. for (auto&& each : vector)
  84. {
  85. each += 42;
  86. }
  87. });
  88.  
  89. return boost::exit_success;
  90. }
Add Comment
Please, Sign In to add comment