get system cpu usage in go

To get the system CPU usage in Go, we can use the cpu package from the golang.org/x/sys/windows/ module. The package provides functions for querying processor information in Windows.

main.go
package main

import (
    "fmt"
    "time"

    "golang.org/x/sys/windows"
)

func main() {
    var idle, kernel, user windows.RUsage

    // Wait for some time to get accurate CPU usage
    time.Sleep(2 * time.Second)

    // Get CPU usage
    if err := windows.GetSystemTimes(&idle, &kernel, &user); err != nil {
        panic(err)
    }

    // Calculate total CPU usage
    idleTime := time.Duration(idle.Time().QuadPart)
    kernelTime := time.Duration(kernel.Time().QuadPart)
    userTime := time.Duration(user.Time().QuadPart)
    total := kernelTime + userTime

    // Calculate percentage of CPU usage
    cpuUsage := float64(total) / float64(total+idleTime) * 100

    fmt.Printf("CPU usage: %.2f%%\n", cpuUsage)
}
726 chars
32 lines

In this example, we use the windows.GetSystemTimes() function to get the system times for idle, kernel, and user processes. We then calculate the total CPU usage by summing the kernel and user times. Finally, we calculate the percentage CPU usage by dividing the total CPU time by the sum of the total and idle times.

related categories

gistlibby LogSnag