-
-
Save mz0/48df62ebcfe116d45c13c86f7a5c7797 to your computer and use it in GitHub Desktop.
Calc proc cpu usage
This file contains 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" | |
"os" | |
"strconv" | |
"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() { | |
if len(os.Args) < 2 { | |
fmt.Printf("need PID, e.g. try \"%s $(pgrep mysqld)\"\n", os.Args[0]) | |
os.Exit(1) | |
} | |
var pid uint64 | |
pid, _ = strconv.ParseUint(os.Args[1], 10, 64) | |
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