cpu_darwin.go 2.5 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
	sysctl, err := exec.LookPath("/usr/sbin/sysctl")
	if err != nil {
		return ret, err
	}
	out, err := exec.Command(sysctl, "machdep.cpu").Output()
40 41 42 43
	if err != nil {
		return ret, err
	}

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

51
		t, err := strconv.ParseInt(values[1], 10, 64)
52
		// err is not checked here because some value is string.
53 54 55 56 57 58 59
		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") {
60 61 62
			if err != nil {
				return ret, err
			}
63
			c.Stepping = int32(t)
64 65 66 67 68 69
		} 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:] {
70 71
				c.Flags = append(c.Flags, strings.ToLower(v))
			}
72 73
		} else if strings.HasPrefix(line, "machdep.cpu.extfeatures") {
			for _, v := range values[1:] {
74 75
				c.Flags = append(c.Flags, strings.ToLower(v))
			}
76
		} else if strings.HasPrefix(line, "machdep.cpu.core_count") {
77 78 79
			if err != nil {
				return ret, err
			}
80
			c.Cores = int32(t)
81
		} else if strings.HasPrefix(line, "machdep.cpu.cache.size") {
82 83 84
			if err != nil {
				return ret, err
			}
85
			c.CacheSize = int32(t)
86 87
		} else if strings.HasPrefix(line, "machdep.cpu.vendor") {
			c.VendorID = values[1]
88
		}
89
	}
90

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

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

	return append(ret, c), nil
}