gopsutil
gopsutil copied to clipboard
CPU usage 0%
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-releaseand the result ofuname -a] - [ ] Mac OS: [paste the result of
sw_versanduname -a - [ ] FreeBSD: [paste the result of
freebsd-version -k -r -uanduname -a] - [ ] OpenBSD: [paste the result of
uname -a]
Could you show us the ignored error?
The error was <nil>
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:
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.