fork download
  1. #include <ctime>
  2. #include <chrono>
  3. #include <ostream>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <algorithm>
  8.  
  9. class StopWatch
  10. {
  11. public:
  12. struct Process
  13. {
  14. Process(std::string name, double time)
  15. :process_name(std::move(name)),
  16. running_time(time)
  17. {}
  18.  
  19. std::string process_name;
  20. double running_time;
  21. };
  22.  
  23. StopWatch()
  24. :running_(false)
  25. {}
  26.  
  27. void Start(const std::string & process)
  28. {
  29. if (running_)
  30. Stop();
  31. current_process_ = process;
  32. running_ = true;
  33. start_time_ = std::chrono::system_clock::now();
  34. }
  35.  
  36. void Stop()
  37. {
  38. if (!running_)
  39. return;
  40. auto now = std::chrono::system_clock::now();
  41. std::chrono::duration<double> duration = now - start_time_;
  42. processes_.emplace_back(
  43. std::move(current_process_), duration.count());
  44. running_ = false;
  45. }
  46.  
  47. static double SystemClockSeconds()
  48. {
  49.  
  50. return (double)clock() / CLOCKS_PER_SEC;
  51. }
  52.  
  53. double operator[] (const std::string & process) const
  54. {
  55. auto it = std::find_if(
  56. processes_.begin(), processes_.end(),
  57. [&](const Process & p) {
  58. return p.process_name == process;
  59. });
  60.  
  61. if (it != processes_.end())
  62. return it->running_time;
  63. return 0.0;
  64. }
  65.  
  66. Process operator[](int index) const {
  67. return processes_[index];
  68. }
  69.  
  70. int size() const { return processes_.size(); }
  71. private:
  72. bool running_;
  73. std::string current_process_;
  74. std::chrono::system_clock::time_point start_time_;
  75. std::vector<Process> processes_;
  76. };
  77.  
  78. std::ostream & operator<<(
  79. std::ostream & os, const StopWatch & watch)
  80. {
  81. for (int i=0; i<watch.size(); ++i)
  82. os << watch[i].process_name << " : "
  83. << watch[i].running_time << "s\n";
  84. return os;
  85. }
  86.  
  87. int main()
  88. {
  89. const int sz = 1000000;
  90. std::vector<long long> src;
  91. std::vector<long long> vi;
  92. std::vector<long long*> vp;
  93.  
  94. for (int i=0; i<sz; ++i)
  95. {
  96. int x = rand();
  97. src.push_back(x);
  98. vi.push_back(x);
  99. }
  100.  
  101. for (int i=0; i<sz; ++i)
  102. {
  103. vp.push_back(&src[i]);
  104. }
  105.  
  106. StopWatch watch;
  107. watch.Start("integers");
  108. std::sort(vi.begin(), vi.end(),
  109. [](long long lhs, long long rhs) {
  110. return lhs < rhs;
  111. });
  112. watch.Stop();
  113.  
  114. watch.Start("pointers");
  115. std::sort(vp.begin(), vp.end(),
  116. [](long long * lhs, long long * rhs) {
  117. return *lhs < *rhs;
  118. });
  119. watch.Stop();
  120.  
  121. std::cout << watch;
  122. }
Success #stdin #stdout 0.58s 3024KB
stdin
Standard input is empty
stdout
integers : 0.129414s
pointers : 0.375247s