memory.go 958 B

123456789101112131415161718192021222324252627282930
  1. package analytic
  2. import (
  3. "fmt"
  4. "math"
  5. "github.com/dustin/go-humanize"
  6. "github.com/pkg/errors"
  7. "github.com/shirou/gopsutil/v4/mem"
  8. "github.com/spf13/cast"
  9. )
  10. func GetMemoryStat() (MemStat, error) {
  11. memoryStat, err := mem.VirtualMemory()
  12. if err != nil {
  13. return MemStat{}, errors.Wrap(err, "error analytic getMemoryStat")
  14. }
  15. return MemStat{
  16. Total: humanize.Bytes(memoryStat.Total),
  17. Used: humanize.Bytes(memoryStat.Used),
  18. Cached: humanize.Bytes(memoryStat.Cached),
  19. Free: humanize.Bytes(memoryStat.Free),
  20. SwapUsed: humanize.Bytes(memoryStat.SwapTotal - memoryStat.SwapFree),
  21. SwapTotal: humanize.Bytes(memoryStat.SwapTotal),
  22. SwapCached: humanize.Bytes(memoryStat.SwapCached),
  23. SwapPercent: cast.ToFloat64(fmt.Sprintf("%.2f",
  24. 100*float64(memoryStat.SwapTotal-memoryStat.SwapFree)/math.Max(float64(memoryStat.SwapTotal), 1))),
  25. Pressure: cast.ToFloat64(fmt.Sprintf("%.2f", memoryStat.UsedPercent)),
  26. }, nil
  27. }