homer512

vector insert benchmark

Mar 24th, 2014
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <vector>
  2. // using std::vector
  3. #include <cstdint>
  4. // using std::uint8_t
  5. #include <cstring>
  6. // using std::memcpy
  7. #include <numeric>
  8. // using std::iota
  9. #include <chrono>
  10. // using std::chrono::high_resolution_clock, std::chrono::microseconds
  11. #include <iostream>
  12. // using std::cout
  13.  
  14. int main()
  15. {
  16.   typedef std::chrono::high_resolution_clock clock_t;
  17.   typedef std::chrono::microseconds us_t;
  18. #define IN_LEN 4096
  19. #ifdef LARGE_BLOCKS
  20.   const std::size_t increments = 512;
  21. #elif defined(SMALL_BLOCKS)
  22.   const std::size_t increments = 4;
  23. #elif defined(BLOCKSIZE)
  24. # if IN_LEN % BLOCKSIZE == 0
  25.   const std::size_t increments = BLOCKSIZE;
  26. # else
  27. #   error 4096 has to be divisible by BLOCKSIZE
  28. # endif
  29. #else
  30. # error Define LARGE_BLOCKS, SMALL_BLOCKS or a custom size with BLOCKSIZE
  31. #endif
  32.   const std::size_t iterations = 1024 * 1024;
  33.   std::uint8_t* input = new std::uint8_t[IN_LEN];
  34.   std::iota(input, input + IN_LEN, std::uint8_t(0));
  35.   clock_t::time_point t0 = clock_t::now();
  36.   for(std::size_t i = 0; i < iterations; ++i) {
  37. #ifdef INSERT
  38.     std::vector<std::uint8_t> out;
  39.     out.reserve(IN_LEN);
  40.     std::uint8_t* const end = input + IN_LEN;
  41.     for(std::uint8_t* pos = input, *next; pos != end; pos = next) {
  42.       next = pos + increments;
  43.       out.insert(out.end(), pos, next);
  44.     }
  45. #elif defined(MEMCPY)
  46.     std::vector<std::uint8_t> out(IN_LEN);
  47.     std::uint8_t* const end = input + IN_LEN;
  48.     std::uint8_t* write_pos = &out[0];
  49.     for(std::uint8_t* pos = input; pos != end; pos += increments) {
  50.       write_pos =
  51.     static_cast<std::uint8_t*>(std::memcpy(write_pos, pos, increments));
  52.       write_pos += increments;
  53.     }
  54. #else
  55. # error Define INSERT or MEMCPY
  56. #endif    
  57.   }
  58.   clock_t::duration t = clock_t::now() - t0;
  59.   us_t us = std::chrono::duration_cast<us_t>(t);
  60.   std::cout << us.count() << " us\n";
  61. }
Advertisement
Add Comment
Please, Sign In to add comment