1
0
mirror of https://github.com/shirou/gopsutil.git synced 2025-04-28 13:48:49 +08:00
shirou_gopsutil/mem/mem_windows.go

98 lines
2.4 KiB
Go
Raw Normal View History

2014-04-18 21:28:00 +09:00
// +build windows
2014-12-30 22:09:05 +09:00
package mem
2014-04-18 21:28:00 +09:00
import (
2017-12-31 15:25:49 +09:00
"context"
"unsafe"
2014-11-27 22:28:05 +09:00
2015-10-20 00:04:57 +09:00
"github.com/shirou/gopsutil/internal/common"
"golang.org/x/sys/windows"
)
var (
2014-11-27 22:28:05 +09:00
procGlobalMemoryStatusEx = common.Modkernel32.NewProc("GlobalMemoryStatusEx")
2017-12-31 15:25:49 +09:00
procGetPerformanceInfo = common.ModPsapi.NewProc("GetPerformanceInfo")
)
2016-04-01 21:34:39 +09:00
type memoryStatusEx struct {
cbSize uint32
dwMemoryLoad uint32
ullTotalPhys uint64 // in bytes
ullAvailPhys uint64
ullTotalPageFile uint64
ullAvailPageFile uint64
ullTotalVirtual uint64
ullAvailVirtual uint64
ullAvailExtendedVirtual uint64
}
func VirtualMemory() (*VirtualMemoryStat, error) {
2017-12-31 15:25:49 +09:00
return VirtualMemoryWithContext(context.Background())
}
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
2016-04-01 21:34:39 +09:00
var memInfo memoryStatusEx
memInfo.cbSize = uint32(unsafe.Sizeof(memInfo))
2014-04-20 01:54:14 +09:00
mem, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memInfo)))
if mem == 0 {
return nil, windows.GetLastError()
}
ret := &VirtualMemoryStat{
Total: memInfo.ullTotalPhys,
Available: memInfo.ullAvailPhys,
UsedPercent: float64(memInfo.dwMemoryLoad),
}
ret.Used = ret.Total - ret.Available
2014-04-18 21:28:00 +09:00
return ret, nil
}
type performanceInformation struct {
2017-12-31 15:25:49 +09:00
cb uint32
commitTotal uint64
commitLimit uint64
commitPeak uint64
physicalTotal uint64
physicalAvailable uint64
2017-12-31 15:25:49 +09:00
systemCache uint64
kernelTotal uint64
kernelPaged uint64
kernelNonpaged uint64
pageSize uint64
handleCount uint32
processCount uint32
threadCount uint32
}
func SwapMemory() (*SwapMemoryStat, error) {
2017-12-31 15:25:49 +09:00
return SwapMemoryWithContext(context.Background())
}
func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
var perfInfo performanceInformation
perfInfo.cb = uint32(unsafe.Sizeof(perfInfo))
mem, _, _ := procGetPerformanceInfo.Call(uintptr(unsafe.Pointer(&perfInfo)), uintptr(perfInfo.cb))
if mem == 0 {
return nil, windows.GetLastError()
}
tot := perfInfo.commitLimit * perfInfo.pageSize
used := perfInfo.commitTotal * perfInfo.pageSize
free := tot - used
var usedPercent float64
if tot == 0 {
usedPercent = 0
} else {
usedPercent = float64(used) / float64(tot)
}
ret := &SwapMemoryStat{
2017-12-31 15:25:49 +09:00
Total: tot,
Used: used,
Free: free,
UsedPercent: usedPercent,
}
2014-04-18 21:28:00 +09:00
return ret, nil
}