Function Signatures
Parameters
If
true, returns statistics for each CPU core individually. If false, returns aggregated statistics for all cores combined.Context for cancellation and timeout control (WithContext variant only).
Return Value
Array of CPU time statistics. Contains one element if
percpu is false, or one element per CPU core if percpu is true.Error if the CPU times could not be retrieved,
nil on success.TimesStat Structure
Fields
CPU identifier. For aggregated stats, typically
"cpu-total". For per-CPU stats, "cpu0", "cpu1", etc.Time spent in user mode (normal processes executing in user mode) in seconds.
Time spent in system mode (kernel executing system calls) in seconds.
Time spent idle (doing nothing) in seconds.
Time spent in user mode with low priority (nice value) in seconds.
Time spent waiting for I/O operations to complete in seconds. Linux only, zero on other platforms.
Time spent servicing hardware interrupts in seconds.
Time spent servicing software interrupts in seconds.
Time stolen by the hypervisor for other virtual machines in seconds. Relevant in virtualized environments.
Time spent running a virtual CPU for a guest operating system in seconds.
Time spent running a niced (low priority) virtual CPU for a guest OS in seconds.
Examples
Get Total CPU Times
Get Per-CPU Times
Using Context with Timeout
Calculate Total CPU Time
Notes
- The
Times()function is a convenience wrapper that callsTimesWithContext()withcontext.Background() - Time values are cumulative since system boot
- To calculate CPU usage percentage over a period, call this function twice with a delay and compare the deltas
- Not all fields are populated on all platforms (e.g.,
Iowaitis Linux-specific) - On some platforms,
GuestandGuestNicetimes are included inUserandNicerespectively - The function returns an empty slice instead of an error if CPU stats are unavailable