Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[windows][mem]: change to use Performance Counter on SwapMemory. #1677

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading