Home  >  Article  >  Backend Development  >  How to Retrieve CPU Usage in Go?

How to Retrieve CPU Usage in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 13:14:01995browse

How to Retrieve CPU Usage in Go?

Retrieving CPU Usage in Go

In Go, obtaining the current CPU usage percentage of both system and user processes necessitates additional functionality beyond the standard library.

Solution:

The package github.com/c9s/goprocinfo provides a convenient solution. This package streamlines data parsing and offers a structured approach to accessing CPU statistics.

Implementation:

Here's how to use goprocinfo:

import "github.com/c9s/goprocinfo/linuxproc"

stat, err := linuxproc.ReadStat("/proc/stat")
if err != nil {
    panic("stat read failed")
}

for _, s := range stat.CPUStats {
    // s.User - Time spent in user mode
    // s.Nice - Time spent in user mode with low priority
    // s.System - Time spent in kernel mode
    // s.Idle - Time spent idle
    // s.IOWait - Time spent waiting for I/O
}

Usage:

This code retrieves CPU usage statistics for each CPU. You can then calculate the percentage of time spent in various states, such as user, kernel, and idle.

The above is the detailed content of How to Retrieve CPU Usage in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn