Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <chrono>
- #include <iostream>
- #include <numeric>
- #include <sstream>
- #include <string>
- #define FWD(...) ::std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)
- std::string data0(50, ' ');
- std::string data1(50, ' ');
- template <typename F>
- void for_iters(F&& f)
- {
- constexpr std::size_t iters = 10000000;
- for(std::size_t n = 0; n < iters; ++n)
- {
- f();
- }
- }
- template <typename F>
- auto bench(F&& f)
- {
- using hr_clock = std::chrono::high_resolution_clock;
- const auto tp = hr_clock::now();
- FWD(f)();
- return hr_clock::now() - tp;
- }
- volatile unsigned int sink;
- template <typename C>
- void to_sink(C&& c)
- {
- sink += std::accumulate(c.begin(), c.end(), 0);
- }
- const auto oss_naive = [] {
- for_iters([] {
- std::ostringstream os;
- os << "Data0: " << data0 << ";Data1=" << data1 << "\n";
- std::string result = os.str();
- to_sink(result);
- });
- };
- const auto oss_avoid_ctor = [] {
- std::ostringstream os;
- for_iters([&os] {
- os.str("");
- os << "Data0: " << data0 << ";Data1=" << data1 << "\n";
- std::string result = os.str();
- to_sink(result);
- });
- };
- inline auto& getOss()
- {
- thread_local std::ostringstream os;
- return os;
- }
- const auto oss_thread_local = [] {
- for_iters([] {
- getOss().str("");
- getOss() << "Data0: " << data0 << ";Data1=" << data1 << "\n";
- std::string result = getOss().str();
- to_sink(result);
- });
- };
- int main()
- {
- const auto print_bench = [](const char* title, auto&& f) {
- const auto t = bench(FWD(f));
- const auto t_ms =
- std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
- std::cout << "'" << title << "' took " << t_ms << " milliseconds\n";
- };
- #define DO_AND_PRINT_BENCH(x) print_bench(#x, x)
- DO_AND_PRINT_BENCH(oss_naive);
- DO_AND_PRINT_BENCH(oss_avoid_ctor);
- DO_AND_PRINT_BENCH(oss_thread_local);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement