Skip to main content

Introduction

The mem package provides cross-platform access to memory statistics, including virtual (RAM) and swap memory information. It abstracts platform-specific differences and provides a consistent API across Linux, Windows, macOS, and BSD systems.

Key Features

Virtual Memory Stats

Get detailed RAM usage statistics including total, available, used memory and platform-specific metrics

Swap Memory Stats

Access swap space information including usage, paging activity, and page fault statistics

Platform Extensions

Linux and Windows specific extended memory information beyond standard metrics

Cross-Platform

Consistent API across Linux, Windows, macOS, FreeBSD, OpenBSD, and Solaris

Package Import

import "github.com/shirou/gopsutil/v4/mem"

Main Functions

VirtualMemory

Retrieves current virtual memory (RAM) statistics.
func VirtualMemory() (*VirtualMemoryStat, error)
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error)
Returns: *VirtualMemoryStat containing detailed memory statistics Example:
v, err := mem.VirtualMemory()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Total: %v MB\n", v.Total/1024/1024)
fmt.Printf("Available: %v MB\n", v.Available/1024/1024)
fmt.Printf("Used: %v MB\n", v.Used/1024/1024)
fmt.Printf("Usage: %.2f%%\n", v.UsedPercent)

SwapMemory

Retrieves current swap memory statistics.
func SwapMemory() (*SwapMemoryStat, error)
func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error)
Returns: *SwapMemoryStat containing swap usage and paging statistics Example:
s, err := mem.SwapMemory()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Total: %v MB\n", s.Total/1024/1024)
fmt.Printf("Used: %v MB\n", s.Used/1024/1024)
fmt.Printf("Usage: %.2f%%\n", s.UsedPercent)

SwapDevices

Retrieves information about individual swap devices (Linux only).
func SwapDevices() ([]*SwapDevice, error)
func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error)
Returns: Slice of *SwapDevice with name and usage per swap device

Data Types

Platform Support

PlatformVirtualMemorySwapMemorySwapDevicesExtended Stats
Linux
Windows
macOS
FreeBSD
OpenBSD
Solaris

CPU Package

CPU usage and information statistics

Disk Package

Disk usage and I/O statistics

Build docs developers (and LLMs) love