fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstring>
  4. #include <ctime>
  5. #define DIM 256
  6. #define LIMIT 1000000
  7.  
  8. using namespace std;
  9.  
  10. class VectorWithMove
  11. {
  12. private:
  13. const int size;
  14. int *array;
  15.  
  16. public:
  17. VectorWithMove(const int new_size) : size(new_size), array(new int [new_size]) {}
  18.  
  19. // copy constructor
  20. VectorWithMove(const VectorWithMove &rhs) : size(rhs.size)
  21. {
  22. // deep copy is required
  23. array = new int [rhs.size];
  24. memcpy(array, rhs.array, rhs.size * sizeof(int));
  25. }
  26.  
  27. // move constructor
  28. VectorWithMove(VectorWithMove &&rhs) : size(rhs.size), array(rhs.array)
  29. {
  30. rhs.array = nullptr;
  31. }
  32.  
  33. int& operator[] (const int index)
  34. {
  35. return array[index];
  36. }
  37.  
  38. int operator[] (const int index) const
  39. {
  40. return array[index];
  41. }
  42.  
  43. VectorWithMove& operator+= (const VectorWithMove &rhs)
  44. {
  45. for(int index=0; index<size; ++index)
  46. array[index] += rhs[index];
  47. return *this;
  48. }
  49.  
  50. VectorWithMove operator+ (const VectorWithMove &rhs) const
  51. {
  52. VectorWithMove temp(*this);
  53. temp += rhs;
  54. return temp;
  55. }
  56.  
  57. ~VectorWithMove() { delete [] array; }
  58. };
  59.  
  60. VectorWithMove&& operator+ (VectorWithMove &&lhs, const VectorWithMove &rhs)
  61. {
  62. lhs += rhs;
  63. return std::move(lhs);
  64. }
  65.  
  66. double runtime_with_move_semantic (const int iterative_limit)
  67. {
  68. clock_t begin, end;
  69. VectorWithMove a(DIM), b(DIM), c(DIM);
  70.  
  71. for(int i=0; i<DIM; ++i) {
  72. a[i] = 0;
  73. b[i] = 1;
  74. c[i] = 2;
  75. }
  76.  
  77. begin = clock();
  78.  
  79. for (int iter; iter<iterative_limit; ++iter) {
  80. VectorWithMove d = a+b+c;
  81. d[iter&DIM] = 2;
  82. }
  83.  
  84. end = clock();
  85.  
  86. return (static_cast<double>(end-begin) / static_cast<double>(CLOCKS_PER_SEC) );
  87. }
  88.  
  89. int main()
  90. {
  91. cout << runtime_with_move_semantic(LIMIT) << '\n';
  92. return 0;
  93. }
Success #stdin #stdout 0.95s 2984KB
stdin
Standard input is empty
stdout
0.94