gopsutil icon indicating copy to clipboard operation
gopsutil copied to clipboard

CPU usage 0%

Open Zoobdude opened this issue 11 months ago • 4 comments

Describe the bug The output of the below code snippet is

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
<nil>

To Reproduce

cpuPercentProcess, err := cpu.Percent(0, true)
fmt.Println(cpuPercentProcess)
fmt.Println(err)


Expected behavior Actual cpu usage is displayed

Environment

  • [x] Windows: Version 10.0.22631 Build 22631
  • [ ] Linux: [paste contents of /etc/os-release and the result of uname -a]
  • [ ] Mac OS: [paste the result of sw_vers and uname -a
  • [ ] FreeBSD: [paste the result of freebsd-version -k -r -u and uname -a]
  • [ ] OpenBSD: [paste the result of uname -a]

Zoobdude avatar Dec 20 '24 16:12 Zoobdude

Could you show us the ignored error?

shirou avatar Dec 21 '24 12:12 shirou

The error was <nil>

Zoobdude avatar Dec 21 '24 12:12 Zoobdude

I encounter a similar problem.

This code created different outcomes in Windows Server 2021.

package main

import (
	"fmt"
	"time"

	"github.com/shirou/gopsutil/v4/cpu"
)

func main() {
	cpuPercentProcess, err := cpu.Percent(0, true)
	fmt.Println(cpuPercentProcess)
	fmt.Println(err)

		totalPercent, err := cpu.Percent(time.Second, false)
		if err != nil {
			fmt.Println("Error fetching total CPU usage:", err)
			return
		}
		fmt.Printf("Total CPU Usage: %.2f%%\n", totalPercent[0])
	
		perCPU, err := cpu.Percent(time.Second, true)
		if err != nil {
			fmt.Println("Error fetching per-CPU usage:", err)
			return
		}
	
		for idx, cp := range perCPU {
			fmt.Printf("CPU %d Usage: %.2f%%\n", idx, cp)
		}
}

The outcome:

PS C:\Users\abc\Downloads> ./testgopsutil.exe
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
<nil>
Total CPU Usage: 0.11%
Error fetching per-CPU usage: received two CPU counts: 24 != 64
PS C:\Users\abc\Downloads> ./testgopsutil.exe
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
<nil>
Total CPU Usage: 0.00%
CPU 0 Usage: 100.00%
CPU 1 Usage: 0.00%
CPU 2 Usage: 100.00%
CPU 3 Usage: 0.00%
CPU 4 Usage: 100.00%
CPU 5 Usage: 0.00%
CPU 6 Usage: 0.00%
CPU 7 Usage: 0.00%
CPU 8 Usage: 100.00%
CPU 9 Usage: 0.00%
CPU 10 Usage: 100.00%
........................
CPU 60 Usage: 0.00%
CPU 61 Usage: 0.00%
CPU 62 Usage: 0.00%
CPU 63 Usage: 0.00%

Total CPU Usage also inconsistent with task manager:

image

xmusphlkg avatar Jan 01 '25 03:01 xmusphlkg

From the document,

If an interval of 0 is given it will compare the current cpu times against the last call.

Therefore, first cpu.Percent(0, true) returns 0 values. If you call cpu.Percent end of the main function in your code, it should return some values.

shirou avatar Jan 06 '25 12:01 shirou