Last active
April 16, 2020 18:46
-
-
Save sklimakov/02441226a96edfc62ebff73f9dfd3db4 to your computer and use it in GitHub Desktop.
Calc proc cpu usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
linuxproc "github.com/c9s/goprocinfo/linux" | |
) | |
func getCPUInfo() (*linuxproc.CPUInfo, error) { | |
return linuxproc.ReadCPUInfo("/proc/cpuinfo") | |
} | |
func readProcessStat(pid uint64) (*linuxproc.ProcessStat, error) { | |
return linuxproc.ReadProcessStat(fmt.Sprintf("/proc/%v/stat", pid)) | |
} | |
func getCPUWorkTime() uint64 { | |
ps, _ := linuxproc.ReadStat("/proc/stat") | |
return ps.CPUStatAll.User + ps.CPUStatAll.Nice + ps.CPUStatAll.System + ps.CPUStatAll.IRQ + ps.CPUStatAll.SoftIRQ + ps.CPUStatAll.Steal + ps.CPUStatAll.Idle + ps.CPUStatAll.IOWait | |
} | |
func getProcWorkTime(pid uint64) uint64 { | |
s, _ := readProcessStat(pid) | |
return s.Stime + s.Utime + uint64(s.Cstime) + uint64(s.Cutime) | |
} | |
func main() { | |
var pid uint64 = 12905 | |
captureInterval := time.Duration(5) * time.Second | |
cpuinfo, _ := getCPUInfo() | |
mul := float64(cpuinfo.NumCPU()) * 100 | |
prevProcCPUsage := getProcWorkTime(pid) | |
prevCPUsage := getCPUWorkTime() | |
for { | |
currentCPUsage := getCPUWorkTime() | |
currentProcCPUsage := getProcWorkTime(pid) | |
fmt.Println(mul * float64(currentProcCPUsage-prevProcCPUsage) / float64(currentCPUsage-prevCPUsage+1)) | |
prevProcCPUsage = currentProcCPUsage | |
prevCPUsage = currentCPUsage | |
time.Sleep(captureInterval) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment