The Process struct provides methods to retrieve detailed memory usage information including RSS, VMS, and other memory metrics.
MemoryInfo
Function Signature
func ( p * Process ) MemoryInfo () ( * MemoryInfoStat , error )
func ( p * Process ) MemoryInfoWithContext ( ctx context . Context ) ( * MemoryInfoStat , error )
Returns generic process memory information including RSS (Resident Set Size) and VMS (Virtual Memory Size).
Return Value
Returns a pointer to MemoryInfoStat:
type MemoryInfoStat struct {
RSS uint64 `json:"rss"` // Resident Set Size (bytes)
VMS uint64 `json:"vms"` // Virtual Memory Size (bytes)
HWM uint64 `json:"hwm"` // High Water Mark (bytes)
Data uint64 `json:"data"` // Data segment size (bytes)
Stack uint64 `json:"stack"` // Stack size (bytes)
Locked uint64 `json:"locked"` // Locked memory (bytes)
Swap uint64 `json:"swap"` // Swapped memory (bytes)
}
Resident Set Size - the amount of physical memory currently used by the process
Virtual Memory Size - the total amount of virtual memory allocated to the process
High Water Mark - the peak RSS usage (maximum RSS since process start)
Amount of locked memory (cannot be swapped to disk)
Amount of memory swapped to disk
Usage Examples
Basic Memory Usage
package main
import (
" fmt "
" github.com/shirou/gopsutil/v4/process "
)
func main () {
p , err := process . NewProcess ( 1234 )
if err != nil {
panic ( err )
}
memInfo , err := p . MemoryInfo ()
if err != nil {
panic ( err )
}
fmt . Printf ( "RSS: %d MB \n " , memInfo . RSS / 1024 / 1024 )
fmt . Printf ( "VMS: %d MB \n " , memInfo . VMS / 1024 / 1024 )
fmt . Printf ( "Swap: %d MB \n " , memInfo . Swap / 1024 / 1024 )
}
Monitor Memory Over Time
package main
import (
" fmt "
" time "
" github.com/shirou/gopsutil/v4/process "
)
func monitorMemory ( pid int32 , duration time . Duration ) {
p , err := process . NewProcess ( pid )
if err != nil {
panic ( err )
}
name , _ := p . Name ()
fmt . Printf ( "Monitoring memory for %s (PID %d ) \n " , name , pid )
ticker := time . NewTicker ( 5 * time . Second )
defer ticker . Stop ()
timeout := time . After ( duration )
for {
select {
case <- ticker . C :
memInfo , err := p . MemoryInfo ()
if err != nil {
fmt . Printf ( "Error: %v \n " , err )
return
}
fmt . Printf ( "[ %s ] RSS: %6d MB | VMS: %6d MB \n " ,
time . Now (). Format ( "15:04:05" ),
memInfo . RSS / 1024 / 1024 ,
memInfo . VMS / 1024 / 1024 )
case <- timeout :
return
}
}
}
func main () {
monitorMemory ( 1234 , 1 * time . Minute )
}
Detect Memory Leaks
package main
import (
" fmt "
" time "
" github.com/shirou/gopsutil/v4/process "
)
func detectMemoryLeak ( pid int32 , thresholdMB uint64 ) {
p , _ := process . NewProcess ( pid )
initialMem , _ := p . MemoryInfo ()
fmt . Printf ( "Initial RSS: %d MB \n " , initialMem . RSS / 1024 / 1024 )
ticker := time . NewTicker ( 10 * time . Second )
defer ticker . Stop ()
for range ticker . C {
currentMem , err := p . MemoryInfo ()
if err != nil {
return
}
currentMB := currentMem . RSS / 1024 / 1024
initialMB := initialMem . RSS / 1024 / 1024
increase := currentMB - initialMB
fmt . Printf ( "Current RSS: %d MB (increased by %d MB) \n " ,
currentMB , increase )
if increase > thresholdMB {
fmt . Printf ( "WARNING: Memory increased by %d MB, threshold: %d MB \n " ,
increase , thresholdMB )
}
}
}
func main () {
detectMemoryLeak ( 1234 , 100 ) // Alert if memory increases by 100MB
}
MemoryPercent
Function Signature
func ( p * Process ) MemoryPercent () ( float32 , error )
func ( p * Process ) MemoryPercentWithContext ( ctx context . Context ) ( float32 , error )
Returns the percentage of total system RAM used by this process.
Usage Example
package main
import (
" fmt "
" github.com/shirou/gopsutil/v4/process "
)
func main () {
p , err := process . NewProcess ( 1234 )
if err != nil {
panic ( err )
}
percent , err := p . MemoryPercent ()
if err != nil {
panic ( err )
}
fmt . Printf ( "Memory usage: %.2f%% \n " , percent )
}
Find Memory-Intensive Processes
package main
import (
" fmt "
" sort "
" github.com/shirou/gopsutil/v4/process "
)
type ProcessMemory struct {
PID int32
Name string
Percent float32
RSS uint64
}
func topMemoryProcesses ( limit int ) {
pids , _ := process . Pids ()
var processes [] ProcessMemory
for _ , pid := range pids {
p , err := process . NewProcess ( pid )
if err != nil {
continue
}
name , err := p . Name ()
if err != nil {
continue
}
percent , err := p . MemoryPercent ()
if err != nil {
continue
}
memInfo , err := p . MemoryInfo ()
if err != nil {
continue
}
processes = append ( processes , ProcessMemory {
PID : pid ,
Name : name ,
Percent : percent ,
RSS : memInfo . RSS ,
})
}
// Sort by memory percentage (descending)
sort . Slice ( processes , func ( i , j int ) bool {
return processes [ i ]. Percent > processes [ j ]. Percent
})
fmt . Printf ( "Top %d memory-consuming processes: \n\n " , limit )
fmt . Printf ( " %-8s %-20s %10s %12s \n " , "PID" , "Name" , "Memory %" , "RSS (MB)" )
fmt . Println ( "------------------------------------------------------" )
for i := 0 ; i < limit && i < len ( processes ); i ++ {
proc := processes [ i ]
fmt . Printf ( " %-8d %-20s %9.2f%% %11d \n " ,
proc . PID ,
proc . Name ,
proc . Percent ,
proc . RSS / 1024 / 1024 )
}
}
func main () {
topMemoryProcesses ( 10 )
}
MemoryInfoEx
Function Signature
func ( p * Process ) MemoryInfoEx () ( * MemoryInfoExStat , error )
func ( p * Process ) MemoryInfoExWithContext ( ctx context . Context ) ( * MemoryInfoExStat , error )
Returns platform-specific extended memory information. The structure varies by operating system and may include additional fields beyond the standard MemoryInfoStat.
The MemoryInfoExStat structure is platform-specific and contains different fields on Linux, Windows, macOS, etc. Check the platform-specific documentation for available fields.
PageFaults
Function Signature
func ( p * Process ) PageFaults () ( * PageFaultsStat , error )
func ( p * Process ) PageFaultsWithContext ( ctx context . Context ) ( * PageFaultsStat , error )
Returns page fault statistics for the process.
PageFaultsStat Structure
type PageFaultsStat struct {
MinorFaults uint64 `json:"minorFaults"`
MajorFaults uint64 `json:"majorFaults"`
ChildMinorFaults uint64 `json:"childMinorFaults"`
ChildMajorFaults uint64 `json:"childMajorFaults"`
}
Minor Faults : Page was loaded into memory but not from disk (soft page fault)
Major Faults : Page had to be loaded from disk (hard page fault)
Example
package main
import (
" fmt "
" github.com/shirou/gopsutil/v4/process "
)
func main () {
p , _ := process . NewProcess ( 1234 )
pageFaults , err := p . PageFaults ()
if err != nil {
panic ( err )
}
fmt . Printf ( "Minor Faults: %d \n " , pageFaults . MinorFaults )
fmt . Printf ( "Major Faults: %d \n " , pageFaults . MajorFaults )
if pageFaults . MajorFaults > 1000 {
fmt . Println ( "High number of major page faults - possible I/O bottleneck" )
}
}
Memory Maps
Function Signature
func ( p * Process ) MemoryMaps ( grouped bool ) ( * [] MemoryMapsStat , error )
func ( p * Process ) MemoryMapsWithContext ( ctx context . Context , grouped bool ) ( * [] MemoryMapsStat , error )
Returns detailed memory maps showing all mapped memory regions (Linux: from /proc/[pid]/smaps).
This function is primarily available on Linux. The grouped parameter determines whether to group memory maps by path.
Comprehensive Monitoring Example
package main
import (
" fmt "
" time "
" github.com/shirou/gopsutil/v4/process "
)
func monitorProcessMemory ( pid int32 ) {
p , err := process . NewProcess ( pid )
if err != nil {
fmt . Printf ( "Error: %v \n " , err )
return
}
name , _ := p . Name ()
fmt . Printf ( "Memory Monitor: %s (PID %d ) \n " , name , pid )
fmt . Println ( "======================================" )
ticker := time . NewTicker ( 10 * time . Second )
defer ticker . Stop ()
for range ticker . C {
// Check if process is still running
running , _ := p . IsRunning ()
if ! running {
fmt . Println ( "Process terminated" )
return
}
// Memory info
memInfo , err := p . MemoryInfo ()
if err != nil {
fmt . Printf ( "Error getting memory info: %v \n " , err )
continue
}
// Memory percentage
memPercent , _ := p . MemoryPercent ()
// Page faults
pageFaults , _ := p . PageFaults ()
fmt . Printf ( " \n [ %s ] \n " , time . Now (). Format ( "2006-01-02 15:04:05" ))
fmt . Printf ( " RSS: %10d MB ( %.2f%% of system RAM) \n " ,
memInfo . RSS / 1024 / 1024 , memPercent )
fmt . Printf ( " VMS: %10d MB \n " , memInfo . VMS / 1024 / 1024 )
fmt . Printf ( " HWM: %10d MB (peak) \n " , memInfo . HWM / 1024 / 1024 )
fmt . Printf ( " Swap: %10d MB \n " , memInfo . Swap / 1024 / 1024 )
if pageFaults != nil {
fmt . Printf ( " Page Faults: %d minor, %d major \n " ,
pageFaults . MinorFaults , pageFaults . MajorFaults )
}
}
}
func main () {
if len ( os . Args ) < 2 {
fmt . Println ( "Usage: program <pid>" )
return
}
var pid int32
fmt . Sscanf ( os . Args [ 1 ], " %d " , & pid )
monitorProcessMemory ( pid )
}
Reads from /proc/[pid]/status and /proc/[pid]/statm files. All fields are supported.
Uses proc_pidinfo() with PROC_PIDTASKINFO. Some fields may not be available.
Uses GetProcessMemoryInfo() API. Maps Windows memory concepts to Unix equivalents.
Uses kvm_getprocs() or sysctl with kern.proc.pid. Field availability varies.
CPU Usage Monitor CPU usage
I/O Counters Monitor I/O statistics
Process Info Get process information
Overview Back to process package overview