| 45 | } |
| 46 | |
| 47 | func getCPUTimes() ([]cputime, error) { |
| 48 | const states = 5 |
| 49 | |
| 50 | clockb, err := unix.SysctlRaw("kern.clockrate") |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | clock := *(*clockinfo)(unsafe.Pointer(&clockb[0])) |
| 55 | cpb, err := unix.SysctlRaw("kern.cp_times") |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | |
| 60 | var cpufreq float64 |
| 61 | if clock.stathz > 0 { |
| 62 | cpufreq = float64(clock.stathz) |
| 63 | } else { |
| 64 | cpufreq = float64(clock.hz) |
| 65 | } |
| 66 | var times []float64 |
| 67 | for len(cpb) >= int(unsafe.Sizeof(int(0))) { |
| 68 | t := *(*int)(unsafe.Pointer(&cpb[0])) |
| 69 | times = append(times, float64(t)/cpufreq) |
| 70 | cpb = cpb[unsafe.Sizeof(int(0)):] |
| 71 | } |
| 72 | |
| 73 | cpus := make([]cputime, len(times)/states) |
| 74 | for i := 0; i < len(times); i += states { |
| 75 | cpu := &cpus[i/states] |
| 76 | cpu.user = times[i] |
| 77 | cpu.nice = times[i+1] |
| 78 | cpu.sys = times[i+2] |
| 79 | cpu.intr = times[i+3] |
| 80 | cpu.idle = times[i+4] |
| 81 | } |
| 82 | return cpus, nil |
| 83 | } |
| 84 | |
| 85 | type statCollector struct { |
| 86 | cpu typedDesc |