liveBook · Manning

CPU usage calculation

As explained in Build and Orchestrator in Go (From Scratch)

CPU usage calculation derives active CPU time by subtracting idle time from total CPU time and dividing by total time.

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

How Build and Orchestrator in Go (From Scratch) covers it

How deep it goes
Descends to CPU counter selection, arithmetic, floating-point conversion, and zero-total handling.
Examples
Uses a Go CpuUsage method over CPUStat fields read from /proc/stat.
What it assumes
Assumes familiarity with Go structs, methods, numeric fields, and Linux /proc metric sources.
What you can do after
Apply it via goprocinfo to expose CPU usage as a percentage.
How it connects
Connects CPU usage with Linux /proc, CPUStat, goprocinfo, and worker metrics.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build and Orchestrator in Go (From Scratch). The section links point to the parts of the book it draws on.