How to get CPU usage

前端 未结 6 1839
刺人心
刺人心 2020-12-22 23:55

My Go program needs to know the current cpu usage percentage of all system and user processes.

How can I obtain that?

6条回答
  •  心在旅途
    2020-12-23 00:42

    The mechanism for getting CPU usage is OS-dependent, since the numbers mean slightly different things to different OS kernels.

    On Linux, you can query the kernel to get the latest stats by reading the pseudo-files in the /proc/ filesystem. These are generated on-the-fly when you read them to reflect the current state of the machine.

    Specifically, the /proc//stat file for each process contains the associated process accounting information. It's documented in proc(5). You're interested specifically in fields utime, stime, cutime and cstime (starting at the 14th field).

    You can calculate the percentage easily enough: just read the numbers, wait some time interval, and read them again. Take the difference, divide by the amount of time you waited, and there's your average. This is precisely what the top program does (as well as all other programs that perform the same service). Bear in mind that you can have over 100% cpu usage if you have more than 1 CPU.

    If you just want a system-wide summary, that's reported in /proc/stat -- calculate your average using the same technique, but you only have to read one file.

提交回复
热议问题