Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cpu usage percent calculation error #1308

Closed

Conversation

sworgod
Copy link

@sworgod sworgod commented Jun 6, 2022

idle = idle + iowait, so busy = user + system + nice + lrq + softirq + steal.
I refer to the algorithm of the psutil project, and also look for relevant information.
The psutil project only calculates the user and system. I understand that the calculation results may be inaccurate.
Then I looked up the information.(http://blog.foool.net/2020/09/%E5%88%A9%E7%94%A8-proc%E7%B2%BE%E7%A1%AE%E8%AE%A1%E7%AE%97linux%E7%B3%BB%E7%BB%9F%E7%9A%84cpu%E5%88%A9%E7%94%A8%E7%8E%87/)
After my test, it should be like this.
My English is not very good.

`idle  = idle + iowait`, so `busy = user + system + nice + lrq + softirq + steal`.
I refer to the algorithm of the psutil project, and also look for relevant information.
The psutil project only calculates the user and system. I understand that the calculation results may be inaccurate.
Then I looked up the information.(http://blog.foool.net/2020/09/%E5%88%A9%E7%94%A8-proc%E7%B2%BE%E7%A1%AE%E8%AE%A1%E7%AE%97linux%E7%B3%BB%E7%BB%9F%E7%9A%84cpu%E5%88%A9%E7%94%A8%E7%8E%87/)
After my test, it should be like this.
My English is not very good.
@shirou
Copy link
Owner

shirou commented Jun 25, 2022

Thank you for point them out! You are true. According to this psutil code, if iowait is defined, then substrcat iowait from busy.

To adapt the psutil implementation , it seems better to use Total(). Therefore, how about the following code? (import runtime is also required to build)

// Deprecated: Total returns the total number of seconds in a CPUTimesStat
// Please do not use this internal function.
func (c TimesStat) Total() float64 {
	total := c.User + c.System + c.Idle + c.Nice + c.Iowait + c.Irq +
		c.Softirq + c.Steal + c.Guest + c.GuestNice

	return total
}


func getAllBusy(t TimesStat) (float64, float64) {
	tot := t.Total()
	if runtime.GOOS == "linux" {
		tot -= t.Guest     // Linux 2.6.24+
		tot -= t.GuestNice // Linux 3.2.0+
	}

	busy := tot - t.Idle - t.Iowait

	return tot, busy
}

I also noticed we expose Total() but it is not implemented in psutil and should be used internally. But we can not delete exposed function in order to keep compatibility. So I want to add Deperecated comments.

@shirou
Copy link
Owner

shirou commented Jul 11, 2022

replaced by #1325. Thank you for your contribution!

@shirou shirou closed this Jul 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants