2021-12-23 05:54:41 +08:00
|
|
|
//go:build darwin && cgo
|
2021-08-18 21:52:13 +08:00
|
|
|
// +build darwin,cgo
|
2016-02-21 03:37:17 +08:00
|
|
|
|
|
|
|
package mem
|
|
|
|
|
|
|
|
/*
|
|
|
|
#include <mach/mach_host.h>
|
2022-07-25 20:22:57 +08:00
|
|
|
#include <mach/vm_page_size.h>
|
2016-02-21 03:37:17 +08:00
|
|
|
*/
|
|
|
|
import "C"
|
|
|
|
|
|
|
|
import (
|
2017-12-31 14:25:49 +08:00
|
|
|
"context"
|
2016-02-21 03:37:17 +08:00
|
|
|
"fmt"
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
|
|
|
// VirtualMemory returns VirtualmemoryStat.
|
|
|
|
func VirtualMemory() (*VirtualMemoryStat, error) {
|
2017-12-31 14:25:49 +08:00
|
|
|
return VirtualMemoryWithContext(context.Background())
|
|
|
|
}
|
|
|
|
|
|
|
|
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
|
2016-02-21 03:37:17 +08:00
|
|
|
count := C.mach_msg_type_number_t(C.HOST_VM_INFO_COUNT)
|
|
|
|
var vmstat C.vm_statistics_data_t
|
|
|
|
|
|
|
|
status := C.host_statistics(C.host_t(C.mach_host_self()),
|
|
|
|
C.HOST_VM_INFO,
|
|
|
|
C.host_info_t(unsafe.Pointer(&vmstat)),
|
|
|
|
&count)
|
|
|
|
|
|
|
|
if status != C.KERN_SUCCESS {
|
|
|
|
return nil, fmt.Errorf("host_statistics error=%d", status)
|
|
|
|
}
|
|
|
|
|
2022-07-25 20:22:57 +08:00
|
|
|
pageSize := uint64(C.vm_kernel_page_size)
|
2016-02-22 14:24:07 +08:00
|
|
|
total, err := getHwMemsize()
|
2016-02-22 04:45:20 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
totalCount := C.natural_t(total / pageSize)
|
2016-02-21 03:37:17 +08:00
|
|
|
|
|
|
|
availableCount := vmstat.inactive_count + vmstat.free_count
|
|
|
|
usedPercent := 100 * float64(totalCount-availableCount) / float64(totalCount)
|
|
|
|
|
2016-02-22 04:45:20 +08:00
|
|
|
usedCount := totalCount - availableCount
|
2016-02-21 03:37:17 +08:00
|
|
|
|
|
|
|
return &VirtualMemoryStat{
|
2016-02-22 04:45:20 +08:00
|
|
|
Total: total,
|
2016-02-21 03:37:17 +08:00
|
|
|
Available: pageSize * uint64(availableCount),
|
|
|
|
Used: pageSize * uint64(usedCount),
|
|
|
|
UsedPercent: usedPercent,
|
|
|
|
Free: pageSize * uint64(vmstat.free_count),
|
|
|
|
Active: pageSize * uint64(vmstat.active_count),
|
|
|
|
Inactive: pageSize * uint64(vmstat.inactive_count),
|
|
|
|
Wired: pageSize * uint64(vmstat.wire_count),
|
|
|
|
}, nil
|
|
|
|
}
|