Retrieving CPU Usage in Go
In Go, obtaining the current CPU usage percentage of both system and user processes necessitates additional functionality beyond the standard library.
Solution:
The package github.com/c9s/goprocinfo provides a convenient solution. This package streamlines data parsing and offers a structured approach to accessing CPU statistics.
Implementation:
Here's how to use goprocinfo:
import "github.com/c9s/goprocinfo/linuxproc" stat, err := linuxproc.ReadStat("/proc/stat") if err != nil { panic("stat read failed") } for _, s := range stat.CPUStats { // s.User - Time spent in user mode // s.Nice - Time spent in user mode with low priority // s.System - Time spent in kernel mode // s.Idle - Time spent idle // s.IOWait - Time spent waiting for I/O }
Usage:
This code retrieves CPU usage statistics for each CPU. You can then calculate the percentage of time spent in various states, such as user, kernel, and idle.
The above is the detailed content of How to Retrieve CPU Usage in Go?. For more information, please follow other related articles on the PHP Chinese website!