ProcessStatisticsSerenity.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Platform.h>
  7. #if !defined(AK_OS_SERENITY)
  8. # error "This file is for Serenity OS only"
  9. #endif
  10. #include <LibCore/File.h>
  11. #include <LibCore/Platform/ProcessStatistics.h>
  12. #include <LibCore/ProcessStatisticsReader.h>
  13. namespace Core::Platform {
  14. ErrorOr<void> update_process_statistics(ProcessStatistics& statistics)
  15. {
  16. static auto proc_all_file = TRY(Core::File::open("/sys/kernel/processes"sv, Core::File::OpenMode::Read));
  17. auto const all_processes = TRY(Core::ProcessStatisticsReader::get_all(*proc_all_file, false));
  18. auto const total_time_scheduled = all_processes.total_time_scheduled;
  19. auto const total_time_scheduled_diff = total_time_scheduled - statistics.total_time_scheduled;
  20. statistics.total_time_scheduled = total_time_scheduled;
  21. for (auto& process : statistics.processes) {
  22. auto it = all_processes.processes.find_if([&](auto& entry) { return entry.pid == process->pid; });
  23. if (!it.is_end()) {
  24. process->memory_usage_bytes = it->amount_resident;
  25. u64 time_process = 0;
  26. for (auto& thread : it->threads) {
  27. time_process += thread.time_user + thread.time_kernel;
  28. }
  29. u64 time_scheduled_diff = time_process - process->time_spent_in_process;
  30. process->time_spent_in_process = time_process;
  31. process->cpu_percent = 0.0;
  32. if (total_time_scheduled_diff > 0) {
  33. process->cpu_percent = static_cast<float>((time_scheduled_diff * 1000) / total_time_scheduled_diff) / 10.0f;
  34. }
  35. } else {
  36. process->memory_usage_bytes = 0;
  37. process->cpu_percent = 0.0;
  38. process->time_spent_in_process = 0;
  39. }
  40. }
  41. return {};
  42. }
  43. }