fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <chrono>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. class muTimer
  9. {
  10. using Clock = std::chrono::high_resolution_clock;
  11. bool active = false;
  12. Clock::duration duration_;
  13. Clock::time_point start_ = Clock::now(), stop_ = Clock::now();
  14.  
  15. muTimer(const muTimer&) = delete;
  16. muTimer& operator=(const muTimer&) = delete;
  17. public:
  18. using ns = std::chrono::nanoseconds;
  19. using mks = std::chrono::microseconds;
  20. using ms = std::chrono::milliseconds;
  21. muTimer() { reset(); start(); }
  22. ~muTimer() = default;
  23. muTimer& reset()
  24. {
  25. duration_ = std::chrono::nanoseconds(0);
  26. active = false;
  27. return *this;
  28. }
  29. muTimer& start()
  30. {
  31. if (!active)
  32. {
  33. start_ = Clock::now();
  34. active = true;
  35. }
  36. return *this;
  37. }
  38. muTimer& stop()
  39. {
  40. if (active)
  41. {
  42. stop_ = Clock::now();
  43. duration_ += stop_ - start_;
  44. active = false;
  45. }
  46. return *this;
  47. }
  48. template<typename T = mks>
  49. unsigned long long duration()
  50. {
  51. return static_cast<unsigned long long>
  52. (std::chrono::duration_cast<T>(stop_-start_).count());
  53. }
  54. };
  55.  
  56.  
  57. int main()
  58. {
  59. const int N = 1000000000;
  60. {
  61. muTimer mt;
  62. for(int i = 0; i < N; ++i);
  63. cout << mt.stop().duration() << endl;
  64. }
  65. {
  66. muTimer mt;
  67. for(int i = N; i > 0; --i);
  68. cout << mt.stop().duration() << endl;
  69. }
  70. }
  71.  
  72.  
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
0
0