From fb162ff529883049605a403ce239c34a83e24746 Mon Sep 17 00:00:00 2001 From: Jakob Borg Date: Mon, 14 Apr 2014 12:02:40 +0200 Subject: [PATCH] More up to date CPU usage indicator --- cmd/syncthing/gui.go | 8 ++++++-- cmd/syncthing/gui_solaris.go | 6 +++--- cmd/syncthing/gui_unix.go | 6 +++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/cmd/syncthing/gui.go b/cmd/syncthing/gui.go index 603a633dd..41e279b5a 100644 --- a/cmd/syncthing/gui.go +++ b/cmd/syncthing/gui.go @@ -155,7 +155,7 @@ func restGetNeed(m *Model, w http.ResponseWriter, params martini.Params) { json.NewEncoder(w).Encode(gfs) } -var cpuUsagePercent float64 +var cpuUsagePercent [10]float64 // The last ten seconds var cpuUsageLock sync.RWMutex func restGetSystem(w http.ResponseWriter) { @@ -168,8 +168,12 @@ func restGetSystem(w http.ResponseWriter) { res["alloc"] = m.Alloc res["sys"] = m.Sys cpuUsageLock.RLock() - res["cpuPercent"] = cpuUsagePercent + var cpusum float64 + for _, p := range cpuUsagePercent { + cpusum += p + } cpuUsageLock.RUnlock() + res["cpuPercent"] = cpusum / 10 w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(res) diff --git a/cmd/syncthing/gui_solaris.go b/cmd/syncthing/gui_solaris.go index 48f787c72..fa53efe98 100644 --- a/cmd/syncthing/gui_solaris.go +++ b/cmd/syncthing/gui_solaris.go @@ -72,8 +72,7 @@ func trackCPUUsage() { var prevTime = time.Now().UnixNano() var rusage prusage_t var pid = os.Getpid() - for { - time.Sleep(10 * time.Second) + for _ = range time.NewTicker(time.Second).C { err := solarisPrusage(pid, &rusage) if err != nil { warnln(err) @@ -84,7 +83,8 @@ func trackCPUUsage() { curUsage := rusage.Pr_utime.Nano() + rusage.Pr_stime.Nano() usageDiff := curUsage - prevUsage cpuUsageLock.Lock() - cpuUsagePercent = 100 * float64(usageDiff) / float64(timeDiff) + copy(cpuUsagePercent[1:], cpuUsagePercent[0:]) + cpuUsagePercent[0] = 100 * float64(usageDiff) / float64(timeDiff) cpuUsageLock.Unlock() prevTime = curTime prevUsage = curUsage diff --git a/cmd/syncthing/gui_unix.go b/cmd/syncthing/gui_unix.go index f9d8e52a7..9d463e498 100644 --- a/cmd/syncthing/gui_unix.go +++ b/cmd/syncthing/gui_unix.go @@ -15,15 +15,15 @@ func trackCPUUsage() { var prevUsage int64 var prevTime = time.Now().UnixNano() var rusage syscall.Rusage - for { - time.Sleep(10 * time.Second) + for _ = range time.NewTicker(time.Second).C { syscall.Getrusage(syscall.RUSAGE_SELF, &rusage) curTime := time.Now().UnixNano() timeDiff := curTime - prevTime curUsage := rusage.Utime.Nano() + rusage.Stime.Nano() usageDiff := curUsage - prevUsage cpuUsageLock.Lock() - cpuUsagePercent = 100 * float64(usageDiff) / float64(timeDiff) + copy(cpuUsagePercent[1:], cpuUsagePercent[0:]) + cpuUsagePercent[0] = 100 * float64(usageDiff) / float64(timeDiff) cpuUsageLock.Unlock() prevTime = curTime prevUsage = curUsage