StopWatch.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #pragma once
  2. #ifdef _WIN32
  3. #include <windows.h>
  4. #else
  5. #include <time.h>
  6. #endif
  7. #ifdef _WIN32
  8. class Stopwatch {
  9. private:
  10. double m_total_time;
  11. LARGE_INTEGER m_start_time;
  12. public:
  13. Stopwatch() { m_total_time = 0.0; }
  14. ~Stopwatch() {}
  15. void Reset() { m_total_time = 0.0; }
  16. void Start() { QueryPerformanceCounter(&m_start_time); }
  17. void Restart()
  18. {
  19. m_total_time = 0.0;
  20. QueryPerformanceCounter(&m_start_time);
  21. }
  22. void Stop()
  23. {
  24. LARGE_INTEGER frequency;
  25. LARGE_INTEGER stop_time;
  26. QueryPerformanceFrequency(&frequency);
  27. QueryPerformanceCounter(&stop_time);
  28. m_total_time +=
  29. ((double)(stop_time.QuadPart - m_start_time.QuadPart) / (double)frequency.QuadPart);
  30. }
  31. double GetTimeInSeconds() { return m_total_time; }
  32. };
  33. #else
  34. class Stopwatch {
  35. private:
  36. double m_total_time;
  37. struct timespec m_start_time;
  38. bool m_is_started;
  39. public:
  40. Stopwatch()
  41. {
  42. m_total_time = 0.0;
  43. m_is_started = false;
  44. }
  45. ~Stopwatch() {}
  46. void Reset() { m_total_time = 0.0; }
  47. void Start()
  48. {
  49. clock_gettime(CLOCK_MONOTONIC, &m_start_time);
  50. m_is_started = true;
  51. }
  52. void Restart()
  53. {
  54. m_total_time = 0.0;
  55. clock_gettime(CLOCK_MONOTONIC, &m_start_time);
  56. m_is_started = true;
  57. }
  58. void Stop()
  59. {
  60. if (m_is_started) {
  61. m_is_started = false;
  62. struct timespec end_time;
  63. clock_gettime(CLOCK_MONOTONIC, &end_time);
  64. m_total_time += (double)(end_time.tv_sec - m_start_time.tv_sec) +
  65. (double)(end_time.tv_nsec - m_start_time.tv_nsec) / 1e9;
  66. }
  67. }
  68. double GetTimeInSeconds()
  69. {
  70. if (m_is_started) {
  71. Stop();
  72. Start();
  73. }
  74. return m_total_time;
  75. }
  76. };
  77. #endif