获取 cpu 使用率并计算使用百分比

发布于 2024-12-29 10:14:03 字数 180 浏览 2 评论 0原文

我需要计算 cpu 使用率并从 linux

/proc/stat 中的 proc 文件聚合它给我数据,但我如何才能知道 cpu 使用的百分比 stat 为我提供了随时运行的核心进程数,但这并不让我了解 cpu 的使用百分比? 我正在 Golang 中进行编码,并且必须在不使用脚本的情况下执行此操作,

提前致谢!

I need to calculate the cpu usage and aggregate it from proc file in linux

/proc/stat gives me data but how would i come to know the % used of cpu at time as
stat gives me the count of processes at cores running at any time which does not give me any idea of %use of cpu?
And i am coding this in Golang and have to do this w/o scripts

Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲娇萝莉攻 2025-01-05 10:14:03

/proc/stat 不仅提供每个核心上的进程数。 man proc 将告诉您该文件的确切格式。从其中复制,这是您应该感兴趣的部分:

   /proc/stat
          cpu  3357 0 4313 1362393
                 The  amount  of  time,  measured  in  units  of   USER_HZ
                 (1/100ths   of   a  second  on  most  architectures,  use
                 sysconf(_SC_CLK_TCK) to obtain the right value), that the
                 system  spent  in  user mode, user mode with low priority
                 (nice), system mode, and  the  idle  task,  respectively.
                 The  last  value should be USER_HZ times the second entry
                 in the uptime pseudo-file.

然后很容易对两个测量之间的idle字段进行减法,这将为您提供该CPU不执行任何操作所花费的时间。您可以提取的另一个值是做某事的时间,这是两个度量之间的差异:

time in user mode + time spent in user mode with low priority + time spent in system mode

然后您将有两个值;一个,A,表示无所事事的时间,另一个,B,表示实际做某事的时间。 B / (A + B) 将为您提供 CPU 繁忙时间的百分比。

/proc/stat does not only give you the count of processes on each core. man proc will tell you the exact format of that file. Copied from it, here is the part you should be interested in:

   /proc/stat
          cpu  3357 0 4313 1362393
                 The  amount  of  time,  measured  in  units  of   USER_HZ
                 (1/100ths   of   a  second  on  most  architectures,  use
                 sysconf(_SC_CLK_TCK) to obtain the right value), that the
                 system  spent  in  user mode, user mode with low priority
                 (nice), system mode, and  the  idle  task,  respectively.
                 The  last  value should be USER_HZ times the second entry
                 in the uptime pseudo-file.

It is then easy to do the substraction of the idle field between two measures, which will give you the time spent not doing anything by this CPU. The other value that you can extract is the time doing something, which is the difference between two measures of:

time in user mode + time spent in user mode with low priority + time spent in system mode

You will then have two values; one, A, is expressing the time doing nothing, and the other, B, the time actually doing something. B / (A + B) will give you the percentage of time the CPU was busy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文