Skip to content

CPU idle rate is negative #1741

Open
Open
@cuijianhui1998

Description

Describe the bug
[A clear and concise description of what the bug is.]
When capturing the idle rate of the CPU, there is an abnormal point. Its value is a negative value, and the value is very large, which is 27960219.

企业微信截图_17302585409765
The code to calculate the CPU idle rate is as follows:

package main

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

func main() {
	var lastStats cpu.TimesStat
	
	// last collect
	lastTimes, _ := cpu.Times(false)
	lastStats = lastTimes[0]
	
	//	 current collect
	curTimes, _ := cpu.Times(false)

	total := totalCPUTime(curTimes[0])
	lastTotal := totalCPUTime(lastStats)
	totalDelta := total - lastTotal
	if totalDelta <= 0 {
		return
	}

	cpuIdle := 100 * (curTimes[0].Idle - lastStats.Idle) / totalDelta
	fmt.Print(cpuIdle)
}

func totalCPUTime(t cpu.TimesStat) float64 {
	total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Idle
	return total
}

To Reproduce
This problem has not been reproduced by restarting the system or modifying the system time. It has only been encountered once so far. I don’t know the cause of this phenomenon and there is no way to reproduce it.

Expected behavior
[A clear and concise description of what you expected to happen.]

Environment (please complete the following information):

[root@localhost ~]# uname -a
Linux localhost 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux


[root@localhost ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

Additional context

go version:  1.19
gopsutil version: github.com/shirou/gopsutil/v3 v3.24.4

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions