func main() { flag.Parse() // convert millicores to percentage millicoresPct := float64(*millicores) / float64(10) duration := time.Duration(*durationSec) * time.Second start := time.Now() first := systemstat.GetProcCPUSample() for time.Now().Sub(start) < duration { cpu := systemstat.GetProcCPUAverage(first, systemstat.GetProcCPUSample(), systemstat.GetUptime().Uptime) if cpu.TotalPct < millicoresPct { doSomething() } else { time.Sleep(sleep) } } }
func (s *stats) GatherStats(percent bool) { s.SysUptime = systemstat.GetUptime() s.ProcUptime = time.Since(s.startTime).Seconds() s.SysMemK = systemstat.GetMemSample() s.LoadAverage = systemstat.GetLoadAvgSample() s.LastCPUSample = s.CurCPUSample s.CurCPUSample = systemstat.GetCPUSample() if s.sysCPUSampled { // we need 2 samples to get an average s.SysCPUAvg = systemstat.GetCPUAverage(s.LastCPUSample, s.CurCPUSample) } // we have at least one sample, subsequent rounds will give us an average s.sysCPUSampled = true s.ProcMemUsedPct = 100 * float64(s.CurProcCPUSample.ProcMemUsedK) / float64(s.SysMemK.MemTotal) s.LastProcCPUSample = s.CurProcCPUSample s.CurProcCPUSample = systemstat.GetProcCPUSample() if s.procCPUSampled { s.ProcCPUAvg = systemstat.GetProcCPUAverage(s.LastProcCPUSample, s.CurProcCPUSample, s.ProcUptime) } s.procCPUSampled = true }