cpu_stats.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ash/hud_display/cpu_stats.h"
  5. #include <cinttypes>
  6. #include <cstdio>
  7. #include "base/files/file_path.h"
  8. #include "base/files/file_util.h"
  9. #include "base/notreached.h"
  10. #include "base/strings/string_util.h"
  11. #include "base/threading/thread_restrictions.h"
  12. namespace ash {
  13. namespace hud_display {
  14. namespace {
  15. constexpr char kProcStatFile[] = "/proc/stat";
  16. std::string ReadProcFile(const base::FilePath& path) {
  17. std::string result;
  18. base::ReadFileToString(path, &result);
  19. return result;
  20. }
  21. } // namespace
  22. CpuStats GetProcStatCPU() {
  23. const std::string stat = ReadProcFile(base::FilePath(kProcStatFile));
  24. // First string should be total Cpu statistics.
  25. if (!base::StartsWith(stat, "cpu ", base::CompareCase::SENSITIVE)) {
  26. NOTREACHED();
  27. return CpuStats();
  28. }
  29. const size_t newline_pos = stat.find('\n');
  30. if (newline_pos == std::string::npos) {
  31. NOTREACHED();
  32. return CpuStats();
  33. }
  34. // Parse first line only.
  35. // Format is described in [man 5 proc] and in kernel source proc/stat.c .
  36. // https://github.com/torvalds/linux/blob/v5.11/fs/proc/stat.c#L153-L163
  37. CpuStats stats;
  38. int assigned =
  39. sscanf(stat.c_str(),
  40. "cpu %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64
  41. " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 "",
  42. &stats.user, &stats.nice, &stats.system, &stats.idle,
  43. &stats.iowait, &stats.irq, &stats.softirq, &stats.steal,
  44. &stats.guest, &stats.guest_nice);
  45. DCHECK_EQ(assigned, 10);
  46. return stats;
  47. }
  48. } // namespace hud_display
  49. } // namespace ash