【问题标题】:Is it possible to get current CPU utilisation from a specific core via /sys in Linux?是否可以通过 Linux 中的 /sys 从特定内核获取当前 CPU 利用率?
【发布时间】:2023-03-30 13:42:01
【问题描述】:

我想编写一个 shellscript 来读取每个核心的当前 CPU 利用率。是否可以从 Linux (CentOS 8) 中的 /sys 目录中读取此内容?我找到了/sys/bus/cpu/drivers/processor/cpu0,它确实给了我相当多的信息(比如当前频率),但我还没有弄清楚如何读取 CPU 利用率。

换句话说:有没有一个文件可以告诉我 Linux 中特定 CPU 内核的当前利用率,特别是 CentOS 8?

【问题讨论】:

  • 快速查看top 的源代码,我会说/proc/stat 就是这个地方。 man proc 并搜索 /proc/stat。
  • 你应该在unix.stackexchange.com问这个

标签: linux bash centos sh cpu-usage


【解决方案1】:

我相信你应该可以从 /proc/stat 中提取信息——以 cpu$N 开头的行,其中 $N 是 0, 1, 2, ...... 例如:

强烈建议阅读其他答案中引用的文章。

cpu0 101840 1 92875 80508446 4038 0 4562 0 0 0
cpu1 81264 0 68829 80842548 4424 0 2902 0 0 0

重复调用会显示更大的值:

cpu  183357 1 162020 161382289 8463 0 7470 0 0 0
cpu0 102003 1 93061 80523961 4038 0 4565 0 0 0
cpu1 81354 0 68958 80858328 4424 0 2905 0 0 0

注意 CPU0 第 5 列(空闲计数)从 80508446 移动到 80523961

每一行的格式

cpuN user-time nice-time system-time idle-time io-wait ireq softirq 偷客guest_nice

所以一个基本的解决方案:

while true ;

   for each cpu
       read current counters, at least user-time system-time and idle 
       usage = current(user-time + system-time) - prev(user-time+system-time)
       idle = current(idle) - prev(idle)
       utilization = usage/(usage+idle)
       // print or whatever.
       set prev=current
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2020-08-30
    • 2013-01-04
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多