My Go program needs to know the current cpu usage percentage of all system and user processes. How can I obtain that? | |||||||||
|
I had a similar issue and never found a lightweight implementation. Here is a slimmed down version of my solution that answers your specific question. I sample the You can also parse the output of
It seems like I'm allowed to link to the full implementation that I wrote on bitbucket; if it's not, feel free to delete this. It only works on linux so far, though: systemstat.go | |||
Check out this package http://github.com/c9s/goprocinfo, goprocinfo package does the parsing stuff for you. | |||||
|
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 Specifically, the 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 If you just want a system-wide summary, that's reported in | |||
You can use the Here is a program issuing the | |||||||||||||||||
|
Here is an OS independent solution using Cgo to harness the clock() function provided by C standard library: | |||||||||||||
|
联系客服