简体   繁体   English

如何获得像“top”命令一样的per-cpu统计信息(system,idle,nice,...)?

[英]How do I get per-cpu stats (system, idle, nice, …) like the “top” command does?

On linux, I'd like to know what "C" API to call to get the per-cpu stats. 在linux上,我想知道要调用什么“C”API来获取per-cpu统计信息。

I know about and could read /proc/loadavg from within my app, but this is the system-wide load avarages, not the per-cpu information. 我知道并且可以在我的应用程序中读取/proc/loadavg ,但这是系统范围的加载avarages,而不是per-cpu信息。 I want to tell the individual CPUs or cores apart. 我想分开各个CPU或核心。

As an example of an application that does this, When I run top and press "1", I can see the 4 or 8 processors/cores like this: 作为执行此操作的应用程序的示例,当我运行top并按“1”时,我可以看到4或8个处理器/核心,如下所示:

Cpu0  :  4.5%us,  0.0%sy,  0.0%ni, 95.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu1  : 42.2%us,  6.2%sy,  0.5%ni, 51.2%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu2  :  3.0%us,  1.5%sy,  0.0%ni, 94.5%id,  0.0%wa,  0.0%hi,  1.0%si,  0.0%st
Cpu3  :  7.0%us,  4.7%sy,  0.0%ni, 88.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

I've tried to strace top but this led to a rat's nest. 我曾尝试过strace top但这导致了一只老鼠的窝。

The file you want is /proc/stat . 你想要的文件是/proc/stat (You might want to refer to fs/proc/stat.c in the Linux kernel source.) (您可能希望在Linux内核源代码中引用fs/proc/stat.c

这不是一个真正的答案,但我会看一下top的源代码。

I guess kernel file timer.c may be of some importance in this scenario to calculate load averages. 我想内核文件timer.c在这种情况下可能具有一定的重要性来计算负载平均值。 From the file timer.c function calc_load() 从文件timer.c函数calc_load()

unsigned long avenrun[3];

static inline void calc_load(unsigned long ticks) 
{

    unsigned long active_tasks; /* fixed-point */
    static int count = LOAD_FREQ;

    count -= ticks;
    if (count < 0) {
        count += LOAD_FREQ;
        active_tasks = count_active_tasks();
        CALC_LOAD(avenrun[0], EXP_1, active_tasks);
        CALC_LOAD(avenrun[1], EXP_5, active_tasks);
        CALC_LOAD(avenrun[2], EXP_15, active_tasks);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM