Skip to main content

Overview

The SwapMemoryStat struct contains swap space usage statistics and paging activity metrics. Swap memory is disk space used as virtual memory when physical RAM is full.

Struct Definition

type SwapMemoryStat struct {
    Total       uint64  `json:"total"`
    Used        uint64  `json:"used"`
    Free        uint64  `json:"free"`
    UsedPercent float64 `json:"usedPercent"`
    Sin         uint64  `json:"sin"`
    Sout        uint64  `json:"sout"`
    PgIn        uint64  `json:"pgIn"`
    PgOut       uint64  `json:"pgOut"`
    PgFault     uint64  `json:"pgFault"`

    // Linux specific numbers
    PgMajFault uint64 `json:"pgMajFault"`
}

Fields

Cross-Platform Fields

Total

  • Type: uint64
  • Description: Total swap space size in bytes
  • Example: 8589934592 (8 GB)
  • Note: Will be 0 if no swap is configured

Used

  • Type: uint64
  • Description: Amount of swap space currently in use in bytes
  • Calculation: Total - Free

Free

  • Type: uint64
  • Description: Amount of unused swap space in bytes
  • Note: Equal to Total when no swap is being used

UsedPercent

  • Type: float64
  • Description: Percentage of swap space in use (0.0 to 100.0)
  • Calculation: (Used / Total) * 100
  • Example: 23.5 means 23.5% of swap is in use
  • Performance indicator: High values may indicate memory pressure

Paging Activity Fields

These fields track memory page movement between RAM and swap. Higher values indicate more paging activity.

Sin

  • Type: uint64
  • Description: Number of bytes swapped in from disk to memory since boot
  • Platform availability: Linux, BSD, some Unix systems
  • Performance note: High values indicate the system is reading from swap frequently

Sout

  • Type: uint64
  • Description: Number of bytes swapped out from memory to disk since boot
  • Platform availability: Linux, BSD, some Unix systems
  • Performance note: High values indicate the system is writing to swap frequently

PgIn

  • Type: uint64
  • Description: Number of pages paged in from disk
  • Platform availability: Linux, BSD
  • Note: Includes all page-ins, not just swap (e.g., file-backed pages)

PgOut

  • Type: uint64
  • Description: Number of pages paged out to disk
  • Platform availability: Linux, BSD
  • Note: Includes all page-outs, not just swap

PgFault

  • Type: uint64
  • Description: Total number of page faults (both major and minor) since boot
  • Platform availability: Linux, BSD, some Unix systems
  • Note: This is a cumulative counter
  • Minor fault: Page was in memory but not in the process’s page table
  • Major fault: Page had to be loaded from disk (see PgMajFault)

Linux Specific Fields

PgMajFault

  • Type: uint64
  • Description: Number of major page faults since boot (page had to be loaded from disk)
  • Platform: Linux only
  • Source: /proc/vmstat or cgroup v2 memory.stat
  • Performance indicator: High values indicate heavy disk I/O for paging
  • Reference: Linux cgroup v2 documentation

Methods

String

func (m SwapMemoryStat) String() string
Returns a JSON string representation of the struct. Example output:
{
  "total": 8589934592,
  "used": 2013265920,
  "free": 6576668672,
  "usedPercent": 23.4,
  "sin": 1048576000,
  "sout": 2097152000,
  "pgIn": 5242880,
  "pgOut": 10485760,
  "pgFault": 31457280,
  "pgMajFault": 1024
}

Usage Example

package main

import (
    "fmt"
    "log"
    
    "github.com/shirou/gopsutil/v4/mem"
)

func main() {
    s, err := mem.SwapMemory()
    if err != nil {
        log.Fatal(err)
    }

    // Check if swap is configured
    if s.Total == 0 {
        fmt.Println("No swap space configured")
        return
    }

    // Basic swap statistics
    fmt.Printf("Total Swap: %v GB\n", s.Total/1024/1024/1024)
    fmt.Printf("Used Swap: %v GB\n", s.Used/1024/1024/1024)
    fmt.Printf("Free Swap: %v GB\n", s.Free/1024/1024/1024)
    fmt.Printf("Swap Usage: %.2f%%\n", s.UsedPercent)

    // Paging activity (platform dependent)
    if s.Sin > 0 || s.Sout > 0 {
        fmt.Printf("\nPaging Activity (since boot):\n")
        fmt.Printf("  Swapped In: %v MB\n", s.Sin/1024/1024)
        fmt.Printf("  Swapped Out: %v MB\n", s.Sout/1024/1024)
    }

    // Page faults
    if s.PgFault > 0 {
        fmt.Printf("\nPage Faults: %v\n", s.PgFault)
    }
    if s.PgMajFault > 0 {
        fmt.Printf("Major Page Faults: %v\n", s.PgMajFault)
    }

    // Performance warning
    if s.UsedPercent > 80 {
        fmt.Println("\nWARNING: Swap usage is high. Consider adding more RAM.")
    }
}

Monitoring Swap Performance

To monitor swap activity over time, you can poll SwapMemory() periodically and calculate deltas:
package main

import (
    "fmt"
    "time"
    
    "github.com/shirou/gopsutil/v4/mem"
)

func main() {
    // Get initial values
    prev, _ := mem.SwapMemory()
    
    time.Sleep(5 * time.Second)
    
    // Get new values
    curr, _ := mem.SwapMemory()
    
    // Calculate deltas (new paging activity)
    sinDelta := curr.Sin - prev.Sin
    soutDelta := curr.Sout - prev.Sout
    
    if sinDelta > 0 || soutDelta > 0 {
        fmt.Printf("Swap activity in last 5 seconds:\n")
        fmt.Printf("  Swapped in: %v KB\n", sinDelta/1024)
        fmt.Printf("  Swapped out: %v KB\n", soutDelta/1024)
    } else {
        fmt.Println("No swap activity detected")
    }
}

SwapDevice Struct

For Linux systems, you can get per-device swap information:
type SwapDevice struct {
    Name      string `json:"name"`
    UsedBytes uint64 `json:"usedBytes"`
    FreeBytes uint64 `json:"freeBytes"`
}

Fields

  • Name (string): Device name or file path (e.g., /dev/sda2, /swapfile)
  • UsedBytes (uint64): Bytes in use on this swap device
  • FreeBytes (uint64): Bytes available on this swap device

Usage

devices, err := mem.SwapDevices()
if err != nil {
    log.Fatal(err)
}

for _, dev := range devices {
    fmt.Printf("Device: %s\n", dev.Name)
    fmt.Printf("  Used: %v MB\n", dev.UsedBytes/1024/1024)
    fmt.Printf("  Free: %v MB\n", dev.FreeBytes/1024/1024)
}

Platform Behavior

Linux

  • All fields populated from /proc/meminfo, /proc/vmstat, and /proc/swaps
  • PgMajFault available from /proc/vmstat
  • SwapDevices() function available

Windows

  • Basic swap fields available (Total, Used, Free, UsedPercent)
  • Paging fields may be 0 or limited
  • Uses Windows API GlobalMemoryStatusEx and GetPerformanceInfo

macOS / BSD

  • Basic swap fields available
  • Some paging fields available depending on the specific BSD variant
  • Values obtained from sysctl calls

Other Unix

  • Platform-dependent field availability
  • Basic fields typically available, paging activity may be limited

Performance Considerations

High swap usage or frequent paging activity can severely impact system performance. Monitor these metrics:
  • UsedPercent > 50%: System may be under memory pressure
  • UsedPercent > 80%: Consider adding more RAM
  • High Sin/Sout delta: Active swapping indicates insufficient RAM
  • High PgMajFault rate: Disk I/O bottleneck due to paging

See Also

Build docs developers (and LLMs) love