fork download
  1. #include <cstdlib>
  2. #include <cstring>
  3. #include <ctime>
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <vector>
  7.  
  8. class stopwatch
  9. {
  10. clock_t last_;
  11. public:
  12. stopwatch()
  13. {
  14. reset();
  15. }
  16. void reset()
  17. {
  18. last_ = std::clock();
  19. }
  20. double time()
  21. {
  22. return (std::clock() - last_) / static_cast<double>(CLOCKS_PER_SEC);
  23. }
  24. };
  25.  
  26. void my_copy(void* dst, const void* src, std::size_t size)
  27. {
  28. std::size_t pack_size = size / sizeof(long long);
  29. std::size_t leftover_size = size - pack_size * sizeof(long long);
  30.  
  31. while (pack_size--)
  32. *(long long*)dst = *(long long*)src;
  33.  
  34. while (leftover_size--)
  35. *(char*)dst = *(char*)src;
  36. }
  37.  
  38. int main()
  39. {
  40. std::vector<char> source(52428800), destination(52428800);
  41. std::generate(source.begin(), source.end(), rand);
  42.  
  43. {
  44. stopwatch w;
  45. for (int i = 10; i--; )
  46. std::copy(source.begin(), source.end(), destination.begin());
  47. std::cout << "copy time: " << w.time() << '\n';
  48. }
  49.  
  50. {
  51. stopwatch w;
  52. for (int i = 10; i--; )
  53. std::memcpy(destination.data(), source.data(), source.size());
  54. std::cout << "memcpy time: " << w.time() << '\n';
  55. }
  56.  
  57. {
  58. stopwatch w;
  59. for (int i = 10; i--; )
  60. my_copy(destination.data(), source.data(), source.size());
  61. std::cout << "my_copy time: " << w.time() << '\n';
  62. }
  63. }
Success #stdin #stdout 2.08s 2828KB
stdin
Standard input is empty
stdout
copy time: 0.25
memcpy time: 0.25
my_copy time: 0.19