简体   繁体   English

不使用top命令以百分比显示CPU核心使用情况

[英]Display CPU cores usage in percentage without using top command

I am using Java to run a command on Linux. 我正在使用Java在Linux上运行命令。 Since top is an interactive command and need to press 1 to get the info of all the cpu(s) so I cannot use that. 由于top是一个交互式命令,需要按1才能获取所有cpu的信息,所以我不能使用它。 So I am using the following command to get the cpu(s) info: 所以我使用以下命令来获取cpu(s)信息:

cat /proc/stat|grep "^cpu[0-9]* ";sleep 3;cat /proc/stat|grep "^cpu[0-9]* "

I am getting the output as : 我得到的输出为:

cpu  4673683 193 832132 1544221346 142352 1220 171760 0 0
cpu0 2473973 90 524817 769734476 73628 1124 158588 0 0
cpu1 2199709 103 307315 774486870 68723 95 13171 0 0
cpu  4673683 193 832133 1544221744 142352 1220 171760 0 0
cpu0 2473974 90 524817 769734674 73628 1124 158588 0 0
cpu1 2199709 103 307315 774487069 68723 95 13171 0 0

Now my problem is how to get the percentage out of it as top command is showing. 现在我的问题是如何在顶级命令显示时从中获取百分比。

Cpu0  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu1  :  0.0%us,  0.3%sy,  0.0%ni, 99.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

I cannot install any packages like mpstat. 我无法安装像mpstat这样的软件包。

From reading the man page for /proc/stat and this how to page , the numbers represent... 从阅读/ proc / stat手册页以及如何页面 ,数字代表......

...the amount of time the CPU has spent performing different kinds of work. ... CPU执行不同类型工作所花费的时间。 Time units are in USER_HZ or Jiffies (typically hundredths of a second). 时间单位为USER_HZ或Jiffies(通常为百分之一秒)。

With this knowledge, I believe creating the percentages you want are pretty straight forward. 有了这些知识,我相信创造你想要的百分比是非常直接的。 Using the output you gave us, here's how you would do this. 使用你给我们的输出,这是你如何做到这一点。 However, keep in mind that these numbers are going to be an aggregate over the entire time since the computer's/server's last reboot. 但是,请记住,自计算机/服务器上次重新启动以来,这些数字将在整个时间内聚合。

/proc/stat file output: / proc / stat文件输出:

cpu0 2473973 90 524817 769734476 73628 1124 158588 0 0
cpu1 2199709 103 307315 774486870 68723 95 13171 0 0

Some simple math 一些简单的数学

First add total elapsed time units since bootup. 首先添加自启动以来的总耗用时间单位。

 772966696 = 2473973 + 90 + 524817 + 769734476 + 73628 + 1124 + 158588 + 0 + 0

Now calculate those percentages 现在计算这些百分比

cpu0: 2473973/772966696  90/772966696  524817/772966696  769734476/772966696 ...

And format the output 并格式化输出

cpu0: 0.3%us, 0.0%sy, 0.0%ni, 99.5% id ...

Let me know if you need help coding this up but it shouldn't be any harder than reading the file, pulling out the lines you want, splitting the line by space and doing the math above. 如果你需要帮助编码,请告诉我,但它不应该比阅读文件更难,拉出你想要的线条,按空格分割线条并进行上面的数学运算。 Hopefully this makes sense and feel free to ask me any followup questions. 希望这是有道理的,并随时问我任何后续问题。

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

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