cpu_darwin.go 2.4 KB
Newer Older
1 2
// +build darwin

S
Shirou WAKAYAMA 已提交
3
package cpu
4 5

import (
6
	"os/exec"
7 8
	"strconv"
	"strings"
9
)
10

11 12 13 14 15 16 17 18
// sys/resource.h
const (
	CPUser    = 0
	CPNice    = 1
	CPSys     = 2
	CPIntr    = 3
	CPIdle    = 4
	CPUStates = 5
19 20
)

21 22
// default value. from time.h
var ClocksPerSec = float64(128)
23

24
func Times(percpu bool) ([]TimesStat, error) {
25 26 27 28 29 30 31
	if percpu {
		return perCPUTimes()
	}

	return allCPUTimes()
}

32
// Returns only one CPUInfoStat on FreeBSD
33 34
func Info() ([]InfoStat, error) {
	var ret []InfoStat
35

36 37 38 39 40
	out, err := exec.Command("/usr/sbin/sysctl", "machdep.cpu").Output()
	if err != nil {
		return ret, err
	}

41
	c := InfoStat{}
42 43
	for _, line := range strings.Split(string(out), "\n") {
		values := strings.Fields(line)
44 45 46
		if len(values) < 1 {
			continue
		}
47

48
		t, err := strconv.ParseInt(values[1], 10, 64)
49
		// err is not checked here because some value is string.
50 51 52 53 54 55 56
		if strings.HasPrefix(line, "machdep.cpu.brand_string") {
			c.ModelName = strings.Join(values[1:], " ")
		} else if strings.HasPrefix(line, "machdep.cpu.family") {
			c.Family = values[1]
		} else if strings.HasPrefix(line, "machdep.cpu.model") {
			c.Model = values[1]
		} else if strings.HasPrefix(line, "machdep.cpu.stepping") {
57 58 59
			if err != nil {
				return ret, err
			}
60
			c.Stepping = int32(t)
61 62 63 64 65 66
		} else if strings.HasPrefix(line, "machdep.cpu.features") {
			for _, v := range values[1:] {
				c.Flags = append(c.Flags, strings.ToLower(v))
			}
		} else if strings.HasPrefix(line, "machdep.cpu.leaf7_features") {
			for _, v := range values[1:] {
67 68
				c.Flags = append(c.Flags, strings.ToLower(v))
			}
69 70
		} else if strings.HasPrefix(line, "machdep.cpu.extfeatures") {
			for _, v := range values[1:] {
71 72
				c.Flags = append(c.Flags, strings.ToLower(v))
			}
73
		} else if strings.HasPrefix(line, "machdep.cpu.core_count") {
74 75 76
			if err != nil {
				return ret, err
			}
77
			c.Cores = int32(t)
78
		} else if strings.HasPrefix(line, "machdep.cpu.cache.size") {
79 80 81
			if err != nil {
				return ret, err
			}
82
			c.CacheSize = int32(t)
83 84
		} else if strings.HasPrefix(line, "machdep.cpu.vendor") {
			c.VendorID = values[1]
85
		}
86
	}
87

88 89 90 91 92 93 94 95
	// Use the rated frequency of the CPU. This is a static value and does not
	// account for low power or Turbo Boost modes.
	out, err = exec.Command("/usr/sbin/sysctl", "hw.cpufrequency").Output()
	if err != nil {
		return ret, err
	}

	values := strings.Fields(string(out))
96
	mhz, err := strconv.ParseFloat(values[1], 64)
97 98
	if err != nil {
		return ret, err
99
	}
100
	c.Mhz = mhz / 1000000.0
101 102 103

	return append(ret, c), nil
}