mem_darwin_cgo.go 1.4 KB

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