Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
frostbyte73 committed Nov 28, 2023
1 parent c418653 commit 509d3bf
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions utils/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package utils

import (
"fmt"
"time"

"github.com/frostbyte73/core"
Expand Down Expand Up @@ -50,13 +49,7 @@ func NewCPUStats(updateCallback func(idle float64)) (*CPUStats, error) {
return nil, err
}

self, err := procfs.Self()
if err != nil {
return nil, err
}

c := &CPUStats{
pid: self.PID,
platform: p,
warningThrottle: core.NewThrottle(time.Minute),
updateCallback: updateCallback,
Expand Down Expand Up @@ -97,6 +90,7 @@ func (c *CPUStats) monitorCPULoad() {

c.idleCPUs.Store(idle)
idleRatio := idle / c.platform.numCPU()
logger.Infow("cpu load", "load", c.platform.numCPU()-idle)

if idleRatio < 0.1 {
c.warningThrottle(func() { logger.Infow("high cpu load", "load", 1-idleRatio) })
Expand All @@ -120,6 +114,7 @@ func (c *CPUStats) MonitorProcesses(updateCallback func(map[int]float64)) error
if err != nil {
return err
}
logger.Infow("svc process", "pid", self.PID)

ticker := time.NewTicker(time.Second)
defer ticker.Stop()
Expand All @@ -141,40 +136,41 @@ func (c *CPUStats) MonitorProcesses(updateCallback func(map[int]float64)) error
if err != nil {
return err
}

ppids := make(map[int]int)
for _, proc := range procs {
fmt.Print(proc.PID, ", ")
nextStats[proc.PID], err = proc.Stat()
if err != nil {
return err
}
if proc.PID != self.PID {
ppids[proc.PID], err = getPPID(proc.PID)
if err != nil {
return err
}
}
}
fmt.Println()

nextTotalTime := total.CPUTotal.User + total.CPUTotal.Nice + total.CPUTotal.System + total.CPUTotal.Idle

ppids := make(map[int]int)
usage := make(map[int]float64)
all := 0.0
for pid, stat := range nextStats {
t := float64(stat.UTime + stat.STime - prevStats[pid].UTime - prevStats[pid].STime)
s := numCPU*t*100/nextTotalTime - prevTotalTime

if pid == self.PID {
usage[pid] = s
if t == 0 {
continue
}

ppid, err := getPPID(pid)
if err != nil {
return err
}
for ppids[ppid] != self.PID && ppids[ppid] != 0 {
pid = ppid
ppid = ppids[ppid]
for ppids[pid] != self.PID && ppids[pid] != 0 {
// attribute usage to parent process, stopping before service process
pid = ppids[pid]
}

s := numCPU * t * 100 / (nextTotalTime - prevTotalTime)
usage[pid] += s
all += s
}

logger.Infow("cpu usage (proc)", "load", all)
updateCallback(usage)

prevTotalTime = nextTotalTime
Expand Down

0 comments on commit 509d3bf

Please sign in to comment.