fork download
  1.  
  2. #ifndef STOPWATCH_HPP
  3. #define STOPWATCH_HPP
  4.  
  5. #include <chrono>
  6.  
  7. template <typename Clock = std::chrono::steady_clock>
  8. class stopwatch
  9. {
  10. public:
  11. typedef Clock clock;
  12. typedef typename clock::time_point time_point;
  13. typedef typename clock::duration duration;
  14.  
  15. private:
  16. time_point last_;
  17.  
  18. public:
  19. stopwatch()
  20. : last_(clock::now())
  21. {}
  22.  
  23. void reset()
  24. {
  25. *this = stopwatch();
  26. }
  27.  
  28. time_point now() const
  29. {
  30. return clock::now();
  31. }
  32.  
  33. duration elapsed() const
  34. {
  35. return now() - last_;
  36. }
  37.  
  38. duration tick()
  39. {
  40. time_point dummy;
  41. return tick(dummy);
  42. }
  43.  
  44. duration tick(time_point& now_)
  45. {
  46. now_ = now();
  47. auto elapsed = now_ - last_;
  48. last_ = now_;
  49. return elapsed;
  50. }
  51. };
  52.  
  53. typedef stopwatch<> default_stopwatch;
  54.  
  55. template <typename T, typename Rep, typename Period>
  56. T duration_cast(const std::chrono::duration<Rep, Period>& duration)
  57. {
  58. return duration.count() * static_cast<T>(Period::num) / static_cast<T>(Period::den);
  59. }
  60.  
  61. #endif
  62.  
  63.  
  64. // cpp file
  65. #include <iostream>
  66. #include <thread>
  67.  
  68. int main()
  69. {
  70. default_stopwatch sw;
  71. for (unsigned i = 0; i != 50; ++i)
  72. {
  73. std::this_thread::sleep_for(std::chrono::milliseconds(77));
  74. std::cout << duration_cast<double>(sw.elapsed()) << '\n';
  75. }
  76. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
0.077066
0.154193
0.231256
0.308323
0.38539
0.462447
0.539505
0.616561
0.693632
0.770689
0.847744
0.924809
1.00188
1.07894
1.15602
1.23308
1.31014
1.3872
1.46427
1.54134
1.6184
1.69546
1.77253
1.84959
1.92666
2.00372
2.08079
2.15785
2.23493
2.312
2.38905
2.46612
2.54318
2.62025
2.69731
2.77437
2.85144
2.92851
3.00557
3.08264
3.1597
3.23677
3.31383
3.39088
3.46794
3.54495
3.62202
3.69909
3.77615
3.85321