Advertisement
Bisqwit

Copy vs constref benchmark

Aug 3rd, 2023 (edited)
949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | Software | 0 0
  1. #include <map>
  2. #include <string>
  3. #include <chrono>
  4. #include <random>
  5. #include <iostream>
  6.  
  7. __attribute__((noinline))
  8. void test_slow(std::map<std::string, std::string> data); // copy
  9. __attribute__((noinline))
  10. void test_fast(const std::map<std::string, std::string>& data); // const reference
  11.  
  12. int main()
  13. {
  14.     // Just create a huge set of dummy data
  15.     std::map<std::string, std::string> some_data;
  16.     std::cout << "Initializing...\n";
  17.     std::random_device e;
  18.     std::mt19937_64 g(e());
  19.     std::uniform_int_distribution d(' ','~');
  20.     while(some_data.size() < 1000000)
  21.     {
  22.         std::string s1; s1.reserve(64); for(std::size_t n=0; n<64; ++n) s1 += d(g);
  23.         std::string s2; s2.reserve(64); for(std::size_t n=0; n<64; ++n) s2 += d(g);
  24.         some_data.emplace(std::move(s1), std::move(s2));
  25.     }
  26.     auto begin = std::chrono::system_clock::now();
  27.     for(std::size_t n=0; n<32; ++n) test_slow(some_data);
  28.     auto end   = std::chrono::system_clock::now();
  29.     std::cout << std::fixed; std::cout.precision(12);
  30.     std::cout << "Slow method: " << std::chrono::duration<double>(end - begin).count() << " s\n";
  31.  
  32.     auto begin2 = std::chrono::system_clock::now();
  33.  
  34.     for(std::size_t n=0; n<32; ++n) test_fast(some_data);
  35.     auto end2   = std::chrono::system_clock::now();
  36.     std::cout << "Fast method: " << std::chrono::duration<double>(end2 - begin2).count() << " s\n";
  37. }
  38.  
  39. void test_slow(std::map<std::string, std::string> data) // copy
  40. {
  41. }
  42. void test_fast(const std::map<std::string, std::string>& data) // const reference
  43. {
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement