-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathget_cpu_load_darwin_cgo.go
43 lines (34 loc) · 1.19 KB
/
get_cpu_load_darwin_cgo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// +build darwin,cgo
// @link https://github.com/mackerelio/go-osstat/blob/master/cpu/cpu_darwin_cgo.go
package cpuload
import (
"sync/atomic"
"unsafe"
)
// #include <mach/mach_host.h>
// #include <mach/host_info.h>
import "C"
var (
previousTotal uint64
previousIdle uint64
)
// getCPULoad returns the load across all cores from 0 to 1 in 1min AVG value
func getCPULoad() float64 {
var (
cpuLoad C.host_cpu_load_info_data_t
count C.mach_msg_type_number_t = C.HOST_CPU_LOAD_INFO_COUNT
ret = C.host_statistics(C.host_t(C.mach_host_self()), C.HOST_CPU_LOAD_INFO, C.host_info_t(unsafe.Pointer(&cpuLoad)), &count)
)
if ret != C.KERN_SUCCESS {
ErrorLogger.Printf("getCPULoad(): host_statistics failed: %d", ret)
return -1
}
total := uint64(cpuLoad.cpu_ticks[C.CPU_STATE_USER])
total += uint64(cpuLoad.cpu_ticks[C.CPU_STATE_NICE])
total += uint64(cpuLoad.cpu_ticks[C.CPU_STATE_SYSTEM])
total += uint64(cpuLoad.cpu_ticks[C.CPU_STATE_IDLE])
idle := uint64(cpuLoad.cpu_ticks[C.CPU_STATE_IDLE])
totalDiff := total - atomic.SwapUint64(&previousTotal, total)
idleDiff := idle - atomic.SwapUint64(&previousIdle, idle)
return 1 - float64(idleDiff)/float64(totalDiff)
}