Stopwatch.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright (c) 2018 tevador
  3. This file is part of RandomX.
  4. RandomX is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. RandomX is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with RandomX. If not, see<http://www.gnu.org/licenses/>.
  14. */
  15. #pragma once
  16. #include <chrono>
  17. #include <cstdint>
  18. class Stopwatch {
  19. public:
  20. Stopwatch(bool startNow = false) {
  21. reset();
  22. if (startNow) {
  23. start();
  24. }
  25. }
  26. void reset() {
  27. isRunning = false;
  28. elapsed = 0;
  29. }
  30. void start() {
  31. if (!isRunning) {
  32. startMark = std::chrono::high_resolution_clock::now();
  33. isRunning = true;
  34. }
  35. }
  36. void restart() {
  37. startMark = std::chrono::high_resolution_clock::now();
  38. isRunning = true;
  39. elapsed = 0;
  40. }
  41. void stop() {
  42. if (isRunning) {
  43. chrono_t endMark = std::chrono::high_resolution_clock::now();
  44. uint64_t ns = std::chrono::duration_cast<sw_unit>(endMark - startMark).count();
  45. elapsed += ns;
  46. isRunning = false;
  47. }
  48. }
  49. double getElapsed() const {
  50. return getElapsedNanosec() / 1e+9;
  51. }
  52. private:
  53. using chrono_t = std::chrono::high_resolution_clock::time_point;
  54. using sw_unit = std::chrono::nanoseconds;
  55. chrono_t startMark;
  56. uint64_t elapsed;
  57. bool isRunning;
  58. uint64_t getElapsedNanosec() const {
  59. uint64_t elns = elapsed;
  60. if (isRunning) {
  61. chrono_t endMark = std::chrono::high_resolution_clock::now();
  62. uint64_t ns = std::chrono::duration_cast<sw_unit>(endMark - startMark).count();
  63. elns += ns;
  64. }
  65. return elns;
  66. }
  67. };