获取 PID 及其所有子项的 CPU 使用率的 C 程序

标签 c linux profiling

我有一个 C 程序可以解析/proc//stat 目录以计算 5 秒内的平均 CPU 使用率:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define ITERATIONS 5

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf( "usage: %s <PID>\n", argv[0] );
        return(-1);
    }

    long double a[4], b[4];
    long double pidTime = 0.0;
    long int clk;
    int i;
    FILE *fp;
    char stat[1024];

    clk = sysconf(_SC_CLK_TCK);

    if (clk == -1) {
        printf("Could not determine clock ticks per second");
        return(-1);
    }

    char *pidPath = malloc(strlen("/proc/stat/")+strlen(argv[1])+1);
    if (pidPath == NULL) {
        printf("Could not allocate memory for str\n");
        return(-1);
    } else {
        strcpy(pidPath, "/proc/");
        strcat(pidPath, argv[1]);
        strcat(pidPath, "/stat");
    }

    for(i = 0; i < ITERATIONS; i++)
    {
        fp = fopen(pidPath,"r");
        if (fp == NULL) {
            perror(pidPath);
            return(-1);
        } else {
            fgets(stat, sizeof(stat), fp);
            sscanf(stat,"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %Lf %Lf %Lf %Lf %*ld %*ld %*ld %*ld %*llu",&a[0],&a[1],&a[2],&a[3]);
            fclose(fp);
            sleep(1);
        }

        fp = fopen(pidPath,"r");
        if (fp == NULL) {
            perror(pidPath);
            return(-1);
        } else {
            fgets(stat, sizeof(stat), fp);
           sscanf(stat,"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %Lf %Lf %Lf %Lf %*ld %*ld %*ld %*ld %*llu",&b[0],&b[1],&b[2],&b[3]);
            fclose(fp);
        }

        pidTime += (((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3])));
    }

    pidTime = (pidTime / (clk * ITERATIONS));
    printf("pidCPU=%Lf\n", pidTime);
    printf("%ld", clk);
    free(pidPath);
    return(0);
}

据我了解,stat 中的相关字段是:

  • 时间;/** 用户模式 ​​jiffies **/

  • 时间;/** 内核模式 jiffies **/

  • int cutime;/** 用户模式 ​​jiffies with childs **/

  • int 时间;/** 内核模式 jiffies with childs **/

对于单个进程,这很好用,但是当我有一个 fork 或多线程的进程时,它就会崩溃。 cutime 和 cstime 计数器是否仅在父进程等待子进程时才工作?如何计算以 PID 为根的进程树的总使用量?

最佳答案

是的,父级需要等待子级的 CPU 时间被添加进来(参见 getrusage 的手册条目 link )。另见 this answer了解更多详情。

关于获取 PID 及其所有子项的 CPU 使用率的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839560/

相关文章:

c++ - InterlockedIncrement 与 InterlockedIncrementAcquire 与 InterlockedIncrementNoFence

c# - 查找大于 double 值的最小 float

linux - 在bash中对具有多个小数的数字进行排序

gcc - g++/gcc在展开递归内联函数方面的效果如何?

c - 为什么改变随机数生成器会改变 C 中快速排序的运行时间

c - 如何将不同长度的字符串放入指针中,例如 char *output[100]

linux - 获取所有WiFi的SSID和BSSID

linux - 在Raspbian上安装go(golang)

python - 提高 Python cProfile 的输出分辨率(需要更高的输出分辨率)

java - 如何在Eclipse中使用Java显示模拟时间?