Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
128 lines (109 loc) · 2.52 KB
/
Copy pathmain.go
File metadata and controls
128 lines (109 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/process"
)
type procData struct {
times *cpu.TimesStat
path string
}
func snapshot(base string) map[int32]procData {
procs, err := process.Processes()
if err != nil {
return nil
}
data := make(map[int32]procData, len(procs))
for _, p := range procs {
ts, err := p.Times()
if err != nil {
continue
}
var path string
if base == "exe" {
path, _ = p.Exe()
} else {
path, _ = p.Cwd()
}
data[p.Pid] = procData{times: ts, path: path}
}
return data
}
func main() {
base := flag.String("base", "cwd", "aggregation basis: cwd | exe")
interval := flag.Duration("i", 1*time.Second, "update interval")
thresh := flag.Float64("t", 0.5, "display threshold (%)")
maxRows := flag.Int("n", 40, "max rows to display")
flag.Parse()
fmt.Printf("dir-cpu (base=%s, interval=%v) — Ctrl+C to quit\n\n", *base, *interval)
prev := snapshot(*base)
if prev == nil {
fmt.Fprintln(os.Stderr, "error: failed to read processes")
os.Exit(1)
}
time.Sleep(*interval)
for {
curr := snapshot(*base)
if curr == nil {
time.Sleep(*interval)
continue
}
secs := interval.Seconds()
dirCPU := make(map[string]float64)
for pid, c := range curr {
p, ok := prev[pid]
if !ok || c.path == "" || c.path == "/" {
continue
}
delta := (c.times.User + c.times.System) - (p.times.User + p.times.System)
if delta <= 0 {
continue
}
cpuPct := delta / secs * 100
if cpuPct < *thresh {
continue
}
dir := filepath.Clean(c.path)
for {
dirCPU[dir] += cpuPct
if dir == "/" {
break
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
}
type entry struct {
dir string
pct float64
}
list := make([]entry, 0, len(dirCPU))
for d, p := range dirCPU {
list = append(list, entry{d, p})
}
sort.Slice(list, func(i, j int) bool { return list[i].pct > list[j].pct })
fmt.Printf("\033[2J\033[H")
fmt.Printf("CPU%% by %s dir (updated: %s)\n", *base, time.Now().Format("15:04:05"))
fmt.Println("────────────────────────────────────────")
if len(list) == 0 {
fmt.Println("(no significant usage)")
}
for i, e := range list {
if i >= *maxRows {
fmt.Printf(" ... %d more\n", len(list)-i)
break
}
fmt.Printf("%7.1f%% %s\n", e.pct, e.dir)
}
prev = curr
time.Sleep(*interval)
}
}