my xfce4 dotfiles
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB

3 years ago
  1. // Copyright 2019 Roman Perepelitsa.
  2. //
  3. // This file is part of GitStatus.
  4. //
  5. // GitStatus is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GitStatus is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with GitStatus. If not, see <https://www.gnu.org/licenses/>.
  17. #include "timer.h"
  18. #include <sys/resource.h>
  19. #include <sys/time.h>
  20. #include <time.h>
  21. #include <cmath>
  22. #include <limits>
  23. #include "check.h"
  24. #include "logging.h"
  25. namespace gitstatus {
  26. namespace {
  27. double CpuTimeMs() {
  28. auto ToMs = [](const timeval& tv) { return 1e3 * tv.tv_sec + 1e-3 * tv.tv_usec; };
  29. rusage usage = {};
  30. CHECK(getrusage(RUSAGE_SELF, &usage) == 0) << Errno();
  31. return ToMs(usage.ru_utime) + ToMs(usage.ru_stime);
  32. }
  33. double WallTimeMs() {
  34. // An attempt to call clock_gettime on an ancient version of MacOS fails at runtime.
  35. // It's possible to detect the presence of clock_gettime at runtime but I don't have
  36. // an ancient MacOS to test the code. Hence this.
  37. #ifdef __APPLE__
  38. return std::numeric_limits<double>::quiet_NaN();
  39. #else
  40. struct timespec ts;
  41. clock_gettime(CLOCK_MONOTONIC, &ts);
  42. return 1e3 * ts.tv_sec + 1e-6 * ts.tv_nsec;
  43. #endif
  44. }
  45. } // namespace
  46. void Timer::Start() {
  47. cpu_ = CpuTimeMs();
  48. wall_ = WallTimeMs();
  49. }
  50. void Timer::Report(const char* msg) {
  51. double cpu = CpuTimeMs() - cpu_;
  52. if (std::isnan(wall_)) {
  53. LOG(INFO) << "Timing for: " << msg << ": " << cpu << "ms cpu";
  54. } else {
  55. double wall = WallTimeMs() - wall_;
  56. LOG(INFO) << "Timing for: " << msg << ": " << cpu << "ms cpu, " << wall << "ms wall";
  57. }
  58. Start();
  59. }
  60. } // namespace gitstatus