Skip to content

Instantly share code, notes, and snippets.

@gallir
Last active August 2, 2016 22:59
Show Gist options
  • Save gallir/17a2e33fc04de5cffd2b8688951b23fb to your computer and use it in GitHub Desktop.
Save gallir/17a2e33fc04de5cffd2b8688951b23fb to your computer and use it in GitHub Desktop.
cpu idle updaters
func (broker *Broker) updateCPUIdle() {
select {
case broker.cpuUpdateChannel <- true:
default:
}
}
func (broker *Broker) cpuIdleUpdater() {
// Initial values required to get stats
minPeriod := 20 * time.Millisecond
idle, total := getCPUSample()
broker.idleJiffies = idle
broker.totalJiffies = total
broker.updatedJiffies = time.Now()
for {
<-broker.cpuUpdateChannel
now := time.Now()
if broker.updatedJiffies.Add(minPeriod).After(now) {
continue
}
idle, total := getCPUSample()
if total == broker.totalJiffies {
continue
}
alpha := math.Min(1, 0.5*float64(now.Sub(broker.updatedJiffies)/time.Millisecond)/1000)
broker.CPUIdle = float64(idle-broker.idleJiffies) / float64(total-broker.totalJiffies)
broker.CPUIdleAvg = (1-alpha)*broker.CPUIdleAvg + alpha*broker.CPUIdle
broker.idleJiffies = idle
broker.totalJiffies = total
broker.updatedJiffies = now
// Don't update CPU so frequently, waiting here make updateCPUIdle fails to write
time.Sleep(minPeriod)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment