Skip to main content
Returns the amount of time the CPU has spent performing different types of work. Time values are in seconds.

Function Signatures

func Times(percpu bool) ([]TimesStat, error)
func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error)

Parameters

percpu
bool
required
If true, returns statistics for each CPU core individually. If false, returns aggregated statistics for all cores combined.
ctx
context.Context
Context for cancellation and timeout control (WithContext variant only).

Return Value

[]TimesStat
[]TimesStat
Array of CPU time statistics. Contains one element if percpu is false, or one element per CPU core if percpu is true.
error
error
Error if the CPU times could not be retrieved, nil on success.

TimesStat Structure

type TimesStat struct {
    CPU       string  `json:"cpu"`
    User      float64 `json:"user"`
    System    float64 `json:"system"`
    Idle      float64 `json:"idle"`
    Nice      float64 `json:"nice"`
    Iowait    float64 `json:"iowait"`
    Irq       float64 `json:"irq"`
    Softirq   float64 `json:"softirq"`
    Steal     float64 `json:"steal"`
    Guest     float64 `json:"guest"`
    GuestNice float64 `json:"guestNice"`
}

Fields

CPU
string
CPU identifier. For aggregated stats, typically "cpu-total". For per-CPU stats, "cpu0", "cpu1", etc.
User
float64
Time spent in user mode (normal processes executing in user mode) in seconds.
System
float64
Time spent in system mode (kernel executing system calls) in seconds.
Idle
float64
Time spent idle (doing nothing) in seconds.
Nice
float64
Time spent in user mode with low priority (nice value) in seconds.
Iowait
float64
Time spent waiting for I/O operations to complete in seconds. Linux only, zero on other platforms.
Irq
float64
Time spent servicing hardware interrupts in seconds.
Softirq
float64
Time spent servicing software interrupts in seconds.
Steal
float64
Time stolen by the hypervisor for other virtual machines in seconds. Relevant in virtualized environments.
Guest
float64
Time spent running a virtual CPU for a guest operating system in seconds.
GuestNice
float64
Time spent running a niced (low priority) virtual CPU for a guest OS in seconds.

Examples

Get Total CPU Times

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/cpu"
)

func main() {
    times, err := cpu.Times(false)
    if err != nil {
        panic(err)
    }
    
    if len(times) > 0 {
        t := times[0]
        fmt.Printf("CPU: %s\n", t.CPU)
        fmt.Printf("User: %.2f seconds\n", t.User)
        fmt.Printf("System: %.2f seconds\n", t.System)
        fmt.Printf("Idle: %.2f seconds\n", t.Idle)
        fmt.Printf("Iowait: %.2f seconds\n", t.Iowait)
    }
}

Get Per-CPU Times

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/cpu"
)

func main() {
    times, err := cpu.Times(true)
    if err != nil {
        panic(err)
    }
    
    for _, t := range times {
        fmt.Printf("CPU %s:\n", t.CPU)
        fmt.Printf("  User: %.2fs, System: %.2fs, Idle: %.2fs\n",
            t.User, t.System, t.Idle)
    }
}

Using Context with Timeout

package main

import (
    "context"
    "fmt"
    "time"
    "github.com/shirou/gopsutil/v4/cpu"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    
    times, err := cpu.TimesWithContext(ctx, false)
    if err != nil {
        if ctx.Err() == context.DeadlineExceeded {
            fmt.Println("Operation timed out")
        } else {
            panic(err)
        }
        return
    }
    
    fmt.Printf("Retrieved times: %+v\n", times[0])
}

Calculate Total CPU Time

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/cpu"
)

func main() {
    times, err := cpu.Times(false)
    if err != nil {
        panic(err)
    }
    
    if len(times) > 0 {
        t := times[0]
        total := t.User + t.System + t.Idle + t.Nice + t.Iowait + 
                 t.Irq + t.Softirq + t.Steal + t.Guest + t.GuestNice
        
        fmt.Printf("Total CPU time: %.2f seconds\n", total)
        fmt.Printf("User: %.2f%% System: %.2f%% Idle: %.2f%%\n",
            (t.User/total)*100,
            (t.System/total)*100,
            (t.Idle/total)*100)
    }
}

Notes

  • The Times() function is a convenience wrapper that calls TimesWithContext() with context.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., Iowait is Linux-specific)
  • On some platforms, Guest and GuestNice times are included in User and Nice respectively
  • The function returns an empty slice instead of an error if CPU stats are unavailable

Build docs developers (and LLMs) love