How to obtain the CPU usage of processes and systems under Linux system

background

During the development of the SDK, it is necessary to collect process and system-related load information. Among them, CPU usage is a very critical indicator. In the early stages, we used pipelines to get the results returned by the top command. But later it was discovered that there were some anomalies online, that is, the reported CPU usage was 0. Considering that the top command will bring a lot of overhead, and improper use of pipelines is prone to problems, we finally used the proc file system method to obtain the CPU usage.

Design

Insert image description here

  1. Extract the CPU time information of the process from the /proc/pid/stat file.
  2. Extract the system's CPU time information from the /proc/stat file.
  3. Repeat steps 1 and 2 within a certain interval (that is, the statistical period).
  4. Calculate the CPU usage of the process and system during the statistical period based on the two results.

Source code

The timer (statistical period) continuously calls the QuerySysProcessCpuInfo function to activate the dynamic CPU usage within the statistical period.

void QuerySysProcessCpuInfo(void)
{
    
    
  // 每个统计周期内(2s)的系统和进程CPU占用率
  std::ifstream pid_stat_file("/proc/" + std::to_string(getpid()) + "/stat");
  if (!pid_stat_file.is_open()) {
    
    
      return kErrorFatal;
  }
  long utime, stime, cutime, cstime;
  std::string temp;
  for (int i = 0; i < 13; ++i) {
    
    
      pid_stat_file >> temp; // Skip to utime
  }
  pid_stat_file >> utime >> stime >> cutime >> cstime;
  long pid_work = utime + stime + cutime + cstime;
  static long prev_pid_work = 0;

  std::ifstream sys_stat_file("/proc/stat");
  if (!sys_stat_file.is_open()) {
    
    
      return kErrorFatal;
  }
  long user, nice, system, idle;
  std::string cpu;
  sys_stat_file >> cpu >> user >> nice >> system >> idle;
  long total = user + nice + system + idle;
  long work = user + nice + system;
  static long prev_total = 0, prev_work = 0;
  double pid_cpu_usage = 100.0 * (pid_work - prev_pid_work) / (total - prev_total);
  printf("进程CPU占用率: %.2f%%\n", pid_cpu_usage);
  double sys_cpu_usage = 100.0 * (work - prev_work) / (total - prev_total);
  printf("系统CPU占用率: %.2f%%\n", sys_cpu_usage );

  prev_pid_work = pid_work;
  prev_total = total;
  prev_work = work;

  pid_stat_file.close();
  sys_stat_file.close();

  return;
}

Guess you like

Origin blog.csdn.net/weixin_36623563/article/details/130770748