Skip to content

Commit

Permalink
Merge pull request #1677 from shirou/feat/win_mem_use_performance_cou…
Browse files Browse the repository at this point in the history
…nter_on_swap_memory

[windows][mem]: change to use Performance Counter on SwapMemory.
  • Loading branch information
shirou committed Jul 30, 2024
2 parents 262afcf + 1221983 commit 1915e93
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
9 changes: 9 additions & 0 deletions internal/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"errors"
"fmt"
"io"
"math"
"net/url"
"os"
"os/exec"
Expand Down Expand Up @@ -463,3 +464,11 @@ func getSysctrlEnv(env []string) []string {
}
return env
}

// Round places rounds the number 'val' to 'n' decimal places
func Round(val float64, n int) float64 {
// Calculate the power of 10 to the n
pow10 := math.Pow(10, float64(n))
// Multiply the value by pow10, round it, then divide it by pow10
return math.Round(val*pow10) / pow10
}
34 changes: 24 additions & 10 deletions mem/mem_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,26 +77,40 @@ func SwapMemory() (*SwapMemoryStat, error) {
}

func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
// Use the performance counter to get the swap usage percentage
counter, err := common.NewWin32PerformanceCounter("swap_percentage", `\Paging File(_Total)\% Usage`)
if err != nil {
return nil, err
}
usedPercent, err := counter.GetValue()
if err != nil {
return nil, err
}

// Get total memory from performance information
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
totalPhys := perfInfo.physicalTotal * perfInfo.pageSize
totalSys := perfInfo.commitLimit * perfInfo.pageSize
total := totalSys - totalPhys

var used uint64
if total > 0 {
used = uint64(0.01 * usedPercent * float64(total))
} else {
usedPercent = float64(used) / float64(tot) * 100
usedPercent = 0.0
used = 0
}

ret := &SwapMemoryStat{
Total: tot,
Total: total,
Used: used,
Free: free,
UsedPercent: usedPercent,
Free: total - used,
UsedPercent: common.Round(usedPercent, 1),
}

return ret, nil
Expand Down

0 comments on commit 1915e93

Please sign in to comment.