| 1 |
|
| 2 |
|
| 3 |
package mem |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
import "C" |
| 9 |
|
| 10 |
import ( |
| 11 |
"context" |
| 12 |
"fmt" |
| 13 |
"unsafe" |
| 14 |
|
| 15 |
"golang.org/x/sys/unix" |
| 16 |
) |
| 17 |
|
| 18 |
|
| 19 |
func VirtualMemory() (*VirtualMemoryStat, error) { |
| 20 |
return VirtualMemoryWithContext(context.Background()) |
| 21 |
} |
| 22 |
|
| 23 |
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { |
| 24 |
count := C.mach_msg_type_number_t(C.HOST_VM_INFO_COUNT) |
| 25 |
var vmstat C.vm_statistics_data_t |
| 26 |
|
| 27 |
status := C.host_statistics(C.host_t(C.mach_host_self()), |
| 28 |
C.HOST_VM_INFO, |
| 29 |
C.host_info_t(unsafe.Pointer(&vmstat)), |
| 30 |
&count) |
| 31 |
|
| 32 |
if status != C.KERN_SUCCESS { |
| 33 |
return nil, fmt.Errorf("host_statistics error=%d", status) |
| 34 |
} |
| 35 |
|
| 36 |
pageSize := uint64(unix.Getpagesize()) |
| 37 |
total, err := getHwMemsize() |
| 38 |
if err != nil { |
| 39 |
return nil, err |
| 40 |
} |
| 41 |
totalCount := C.natural_t(total / pageSize) |
| 42 |
|
| 43 |
availableCount := vmstat.inactive_count + vmstat.free_count |
| 44 |
usedPercent := 100 * float64(totalCount-availableCount) / float64(totalCount) |
| 45 |
|
| 46 |
usedCount := totalCount - availableCount |
| 47 |
|
| 48 |
return &VirtualMemoryStat{ |
| 49 |
Total: total, |
| 50 |
Available: pageSize * uint64(availableCount), |
| 51 |
Used: pageSize * uint64(usedCount), |
| 52 |
UsedPercent: usedPercent, |
| 53 |
Free: pageSize * uint64(vmstat.free_count), |
| 54 |
Active: pageSize * uint64(vmstat.active_count), |
| 55 |
Inactive: pageSize * uint64(vmstat.inactive_count), |
| 56 |
Wired: pageSize * uint64(vmstat.wire_count), |
| 57 |
}, nil |
| 58 |
} |