Add memory package

This commit is contained in:
世界 2023-09-20 13:49:54 +08:00
parent 1453c7c8c2
commit b1cca65a05
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
3 changed files with 43 additions and 0 deletions

16
common/memory/memory.go Normal file
View file

@ -0,0 +1,16 @@
package memory
import "runtime"
func Total() uint64 {
if nativeAvailable {
return usageNative()
}
return Inuse()
}
func Inuse() uint64 {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
return memStats.StackInuse + memStats.HeapInuse + memStats.HeapIdle - memStats.HeapReleased
}

View file

@ -0,0 +1,18 @@
package memory
// #include <mach/mach.h>
import "C"
import "unsafe"
const nativeAvailable = true
func usageNative() uint64 {
var memoryUsageInByte uint64
var vmInfo C.task_vm_info_data_t
var count C.mach_msg_type_number_t = C.TASK_VM_INFO_COUNT
var kernelReturn C.kern_return_t = C.task_info(C.vm_map_t(C.mach_task_self_), C.TASK_VM_INFO, (*C.integer_t)(unsafe.Pointer(&vmInfo)), &count)
if kernelReturn == C.KERN_SUCCESS {
memoryUsageInByte = uint64(vmInfo.phys_footprint)
}
return memoryUsageInByte
}

View file

@ -0,0 +1,9 @@
//go:build (darwin && !cgo) || !darwin
package memory
const nativeAvailable = false
func usageNative() uint64 {
return 0
}