CPU usage calculation turns Linux CPU counters into a percentage by grouping idle time, summing non-idle time, and dividing active time by total time. section 6.3
Implement the calculation through three explicit steps:
- Treat Idle and IOWait as idle time. section 6.3
- Sum User, Nice, System, IRQ, SoftIRQ, and Steal as non-idle time. section 6.3
- Compute (total − idle) / total, returning 0.00 when total is zero. section 6.3
Listing 6.9 Using the CpuUsage() method to get CPU usage as a percentage
func (s *Stats) CpuUsage() float64 {
idle := s.CpuStats.Idle + s.CpuStats.IOWait
nonIdle := s.CpuStats.User + s.CpuStats.Nice + s.CpuStats.System +
s.CpuStats.IRQ + s.CpuStats.SoftIRQ + s.CpuStats.Steal
total := idle + nonIdle
if total == 0 {
return 0.00
}
return (float64(total) - float64(idle)) / float64(total)
}
The CpuUsage implementation shows the complete calculation, including counter selection, totals, floating-point conversion, and zero handling. section 6.3
