Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. #include <chrono>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <sstream>
  5. #include <string>
  6.  
  7. #define FWD(...) ::std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)
  8.  
  9. std::string data0(50, ' ');
  10. std::string data1(50, ' ');
  11.  
  12. template <typename F>
  13. void for_iters(F&& f)
  14. {
  15. constexpr std::size_t iters = 10000000;
  16. for(std::size_t n = 0; n < iters; ++n)
  17. {
  18. f();
  19. }
  20. }
  21.  
  22. template <typename F>
  23. auto bench(F&& f)
  24. {
  25. using hr_clock = std::chrono::high_resolution_clock;
  26. const auto tp = hr_clock::now();
  27. FWD(f)();
  28. return hr_clock::now() - tp;
  29. }
  30.  
  31. volatile unsigned int sink;
  32.  
  33. template <typename C>
  34. void to_sink(C&& c)
  35. {
  36. sink += std::accumulate(c.begin(), c.end(), 0);
  37. }
  38.  
  39. const auto oss_naive = [] {
  40. for_iters([] {
  41. std::ostringstream os;
  42. os << "Data0: " << data0 << ";Data1=" << data1 << "\n";
  43. std::string result = os.str();
  44. to_sink(result);
  45. });
  46. };
  47.  
  48. const auto oss_avoid_ctor = [] {
  49. std::ostringstream os;
  50.  
  51. for_iters([&os] {
  52. os.str("");
  53. os << "Data0: " << data0 << ";Data1=" << data1 << "\n";
  54. std::string result = os.str();
  55. to_sink(result);
  56. });
  57. };
  58.  
  59. inline auto& getOss()
  60. {
  61. thread_local std::ostringstream os;
  62. return os;
  63. }
  64.  
  65. const auto oss_thread_local = [] {
  66. for_iters([] {
  67. getOss().str("");
  68. getOss() << "Data0: " << data0 << ";Data1=" << data1 << "\n";
  69. std::string result = getOss().str();
  70. to_sink(result);
  71. });
  72. };
  73.  
  74. int main()
  75. {
  76. const auto print_bench = [](const char* title, auto&& f) {
  77. const auto t = bench(FWD(f));
  78. const auto t_ms =
  79. std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
  80.  
  81. std::cout << "'" << title << "' took " << t_ms << " milliseconds\n";
  82. };
  83.  
  84. #define DO_AND_PRINT_BENCH(x) print_bench(#x, x)
  85.  
  86. DO_AND_PRINT_BENCH(oss_naive);
  87. DO_AND_PRINT_BENCH(oss_avoid_ctor);
  88. DO_AND_PRINT_BENCH(oss_thread_local);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement