How to Retrieve CPU Usage in Go?

Mary-Kate Olsen
Release: 2024-11-12 13:14:01
Original
1032 people have browsed it

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template