StopWatch.h 1.9 KB

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