├── .gitignore ├── LICENSE ├── README.md ├── go.mod ├── pidusage.go └── pidusage_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 David 大伟 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pidusage 2 | Cross-platform process cpu % and memory usage of a PID for golang 3 | 4 | Ideas from https://github.com/soyuka/pidusage but just use Golang 5 | 6 | [![Go Report Card](https://goreportcard.com/badge/github.com/struCoder/pidusage)](https://goreportcard.com/report/github.com/struCoder/pidusage) 7 | [![GoDoc](https://godoc.org/github.com/struCoder/pidusage?status.svg)](https://godoc.org/github.com/struCoder/pidusage) 8 | 9 | ## API 10 | 11 | ```golang 12 | import ( 13 | "os" 14 | "github.com/struCoder/pidusage" 15 | ) 16 | 17 | func printStat() { 18 | sysInfo, err := pidusage.GetStat(os.Process.Pid) 19 | } 20 | ``` 21 | 22 | ## How it works 23 | 24 | A check on the `runtime.GOOS` is done to determine the method to use. 25 | 26 | ### Linux 27 | We use `/proc/{pid}/stat` in addition to the the `PAGE_SIZE` and the `CLK_TCK` direclty from `getconf()` command. Uptime comes from `proc/uptime` 28 | 29 | Cpu usage is computed by following [those instructions](http://stackoverflow.com/questions/16726779/how-do-i-get-the-total-cpu-usage-of-an-application-from-proc-pid-stat/16736599#16736599). It keeps an history of the current processor time for the given pid so that the computed value gets more and more accurate. Don't forget to do `unmonitor(pid)` so that history gets cleared. 30 | Cpu usage does not check the child process tree! 31 | 32 | Memory result is representing the RSS (resident set size) only by doing `rss*pagesize`, where `pagesize` is the result of `getconf PAGE_SIZE`. 33 | 34 | ### On darwin, freebsd, solaris 35 | We use a fallback with the `ps -o pcpu,rss -p PID` command to get the same informations. 36 | 37 | Memory usage will also display the RSS only, process cpu usage might differ from a distribution to another. Please check the correspoding `man ps` for more insights on the subject. 38 | 39 | ### On AIX 40 | AIX is tricky because I have no AIX test environement, at the moment we use: `ps -o pcpu,rssize -p PID` but `/proc` results should be more accurate! If you're familiar with the AIX environment and know how to get the same results as we've got with Linux systems. 41 | 42 | ### Windows 43 | Next version will support 44 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/struCoder/pidusage 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /pidusage.go: -------------------------------------------------------------------------------- 1 | package pidusage 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io/ioutil" 7 | "math" 8 | "os/exec" 9 | "path" 10 | "runtime" 11 | "strconv" 12 | "strings" 13 | "sync" 14 | ) 15 | 16 | const ( 17 | statTypePS = "ps" 18 | statTypeProc = "proc" 19 | ) 20 | 21 | // SysInfo will record cpu and memory data 22 | type SysInfo struct { 23 | CPU float64 24 | Memory float64 25 | } 26 | 27 | // Stat will store CPU time struct 28 | type Stat struct { 29 | utime float64 30 | stime float64 31 | cutime float64 32 | cstime float64 33 | start float64 34 | rss float64 35 | uptime float64 36 | } 37 | 38 | type fn func(int) (*SysInfo, error) 39 | 40 | var fnMap map[string]fn 41 | var platform string 42 | var history map[int]Stat 43 | var historyLock sync.Mutex 44 | var eol string 45 | 46 | // Linux platform 47 | var clkTck float64 = 100 // default 48 | var pageSize float64 = 4096 // default 49 | 50 | func init() { 51 | platform = runtime.GOOS 52 | if eol = "\n"; strings.Index(platform, "win") == 0 { 53 | platform = "win" 54 | eol = "\r\n" 55 | } 56 | history = make(map[int]Stat) 57 | fnMap = make(map[string]fn) 58 | fnMap["darwin"] = wrapper("ps") 59 | fnMap["sunos"] = wrapper("ps") 60 | fnMap["freebsd"] = wrapper("ps") 61 | fnMap["openbsd"] = wrapper("proc") 62 | fnMap["aix"] = wrapper("ps") 63 | fnMap["linux"] = wrapper("proc") 64 | fnMap["netbsd"] = wrapper("proc") 65 | fnMap["win"] = wrapper("win") 66 | 67 | if platform == "linux" || platform == "netbsd" || platform == "openbsd" { 68 | initProc() 69 | } 70 | } 71 | 72 | func initProc() { 73 | clkTckStdout, err := exec.Command("getconf", "CLK_TCK").Output() 74 | if err == nil { 75 | clkTck = parseFloat(formatStdOut(clkTckStdout, 0)[0]) 76 | } 77 | 78 | pageSizeStdout, err := exec.Command("getconf", "PAGESIZE").Output() 79 | if err == nil { 80 | pageSize = parseFloat(formatStdOut(pageSizeStdout, 0)[0]) 81 | } 82 | 83 | } 84 | 85 | func wrapper(statType string) func(pid int) (*SysInfo, error) { 86 | return func(pid int) (*SysInfo, error) { 87 | return stat(pid, statType) 88 | } 89 | } 90 | 91 | func formatStdOut(stdout []byte, userfulIndex int) []string { 92 | infoArr := strings.Split(string(stdout), eol)[userfulIndex] 93 | ret := strings.Fields(infoArr) 94 | return ret 95 | } 96 | 97 | func parseFloat(val string) float64 { 98 | floatVal, _ := strconv.ParseFloat(val, 64) 99 | return floatVal 100 | } 101 | 102 | func statFromPS(pid int) (*SysInfo, error) { 103 | sysInfo := &SysInfo{} 104 | args := "-o pcpu,rss -p" 105 | if platform == "aix" { 106 | args = "-o pcpu,rssize -p" 107 | } 108 | stdout, _ := exec.Command("ps", args, strconv.Itoa(pid)).Output() 109 | ret := formatStdOut(stdout, 1) 110 | if len(ret) == 0 { 111 | return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid)) 112 | } 113 | sysInfo.CPU = parseFloat(ret[0]) 114 | sysInfo.Memory = parseFloat(ret[1]) * 1024 115 | return sysInfo, nil 116 | } 117 | 118 | func statFromProc(pid int) (*SysInfo, error) { 119 | sysInfo := &SysInfo{} 120 | uptimeFileBytes, err := ioutil.ReadFile(path.Join("/proc", "uptime")) 121 | if err != nil { 122 | return nil, err 123 | } 124 | uptime := parseFloat(strings.Split(string(uptimeFileBytes), " ")[0]) 125 | 126 | procStatFileBytes, err := ioutil.ReadFile(path.Join("/proc", strconv.Itoa(pid), "stat")) 127 | if err != nil { 128 | return nil, err 129 | } 130 | splitAfter := strings.SplitAfter(string(procStatFileBytes), ")") 131 | 132 | if len(splitAfter) == 0 || len(splitAfter) == 1 { 133 | return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid)) 134 | } 135 | infos := strings.Split(splitAfter[1], " ") 136 | stat := &Stat{ 137 | utime: parseFloat(infos[12]), 138 | stime: parseFloat(infos[13]), 139 | cutime: parseFloat(infos[14]), 140 | cstime: parseFloat(infos[15]), 141 | start: parseFloat(infos[20]) / clkTck, 142 | rss: parseFloat(infos[22]), 143 | uptime: uptime, 144 | } 145 | 146 | _stime := 0.0 147 | _utime := 0.0 148 | 149 | historyLock.Lock() 150 | defer historyLock.Unlock() 151 | 152 | _history := history[pid] 153 | 154 | if _history.stime != 0 { 155 | _stime = _history.stime 156 | } 157 | 158 | if _history.utime != 0 { 159 | _utime = _history.utime 160 | } 161 | total := stat.stime - _stime + stat.utime - _utime 162 | total = total / clkTck 163 | 164 | seconds := stat.start - uptime 165 | if _history.uptime != 0 { 166 | seconds = uptime - _history.uptime 167 | } 168 | 169 | seconds = math.Abs(seconds) 170 | if seconds == 0 { 171 | seconds = 1 172 | } 173 | 174 | history[pid] = *stat 175 | sysInfo.CPU = (total / seconds) * 100 176 | sysInfo.Memory = stat.rss * pageSize 177 | return sysInfo, nil 178 | } 179 | 180 | func stat(pid int, statType string) (*SysInfo, error) { 181 | switch statType { 182 | case statTypePS: 183 | return statFromPS(pid) 184 | case statTypeProc: 185 | return statFromProc(pid) 186 | default: 187 | return nil, fmt.Errorf("Unsupported OS %s", runtime.GOOS) 188 | } 189 | } 190 | 191 | // GetStat will return current system CPU and memory data 192 | func GetStat(pid int) (*SysInfo, error) { 193 | sysInfo, err := fnMap[platform](pid) 194 | return sysInfo, err 195 | } 196 | -------------------------------------------------------------------------------- /pidusage_test.go: -------------------------------------------------------------------------------- 1 | package pidusage 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | var pid = os.Getpid() 9 | 10 | func BenchmarkGetStat(b *testing.B) { 11 | for i := 0; i < b.N; i++ { 12 | GetStat(pid) 13 | } 14 | } 15 | 16 | // Before optimize 17 | // $ go clean -testcache && go test -test.v -bench=BenchmarkGetStat 18 | // goos: linux 19 | // goarch: amd64 20 | // pkg: github.com/struCoder/pidusage 21 | // BenchmarkGetStat 22 | // BenchmarkGetStat-12 470 2690727 ns/op 23 | // PASS 24 | // ok github.com/struCoder/pidusage 1.533s 25 | 26 | // After optimize 27 | // $ go clean -testcache && go test -test.v -bench=BenchmarkGetStat 28 | // goos: linux 29 | // goarch: amd64 30 | // pkg: github.com/struCoder/pidusage 31 | // BenchmarkGetStat 32 | // BenchmarkGetStat-12 28416 36234 ns/op 33 | // PASS 34 | // ok github.com/struCoder/pidusage 1.472s 35 | --------------------------------------------------------------------------------