Тип runtime.MemStats
Тип runtime.MemStats предоставляет детальную информацию
о состоянии системы управления памятью Go. Он включает данные
о распределении памяти, количестве объектов, времени сборки мусора
и других важных метриках. Статистика заполняется при вызове
функции runtime.ReadMemStats.
Синтаксис
import "runtime"
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
Основные поля
Структура содержит множество полей, разделенных на логические группы:
type MemStats struct {
Alloc uint64 // bytes allocated and not yet freed
TotalAlloc uint64 // bytes allocated (even if freed)
Sys uint64 // bytes obtained from system
Lookups uint64 // number of pointer lookups
Mallocs uint64 // number of mallocs
Frees uint64 // number of frees
HeapAlloc uint64 // heap bytes allocated and not freed
HeapSys uint64 // heap bytes obtained from system
HeapIdle uint64 // heap bytes waiting to be used
HeapInuse uint64 // heap bytes in use
HeapReleased uint64 // heap bytes released to OS
HeapObjects uint64 // number of allocated objects
StackInuse uint64 // bytes used by stack allocator
StackSys uint64 // bytes obtained from system for stack
MSpanInuse uint64 // bytes used by mspan structures
MSpanSys uint64 // bytes obtained for mspan structures
MCacheInuse uint64 // bytes used by mcache structures
MCacheSys uint64 // bytes obtained for mcache structures
BuckHashSys uint64 // bytes used by profiling bucket hash table
GCSys uint64 // bytes used for garbage collection metadata
OtherSys uint64 // bytes used for other system allocations
NextGC uint64 // next target heap size for GC
LastGC uint64 // time of last GC (nanoseconds since epoch)
PauseTotalNs uint64 // total GC pause time
PauseNs [256]uint64 // circular buffer of GC pause times
PauseEnd [256]uint64 // circular buffer of GC pause end times
NumGC uint32 // number of completed GC cycles
NumForcedGC uint32 // number of forced GC cycles
GCCPUFraction float64 // fraction of CPU time used by GC
EnableGC bool // true if GC is enabled
DebugGC bool // true if debug GC is enabled
BySize [61]struct {
Size uint32
Mallocs uint64
Frees uint64
}
}
Пример получения статистики
Получим основные показатели использования памяти:
package main
import (
"fmt"
"runtime"
)
func main() {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
fmt.Printf("Alloc = %d bytes\n", stats.Alloc)
fmt.Printf("TotalAlloc = %d bytes\n", stats.TotalAlloc)
fmt.Printf("Sys = %d bytes\n", stats.Sys)
fmt.Printf("NumGC = %d\n", stats.NumGC)
}
Результат выполнения кода:
"Alloc = 123456 bytes"
"TotalAlloc = 1234567 bytes"
"Sys = 2345678 bytes"
"NumGC = 42"
Пример мониторинга памяти
Отследим изменения памяти после выделения объектов:
package main
import (
"fmt"
"runtime"
)
func main() {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
before := stats.HeapAlloc
// Allocate some memory
s := make([]int, 1000000)
for i := range s {
s[i] = i
}
runtime.ReadMemStats(&stats)
after := stats.HeapAlloc
fmt.Printf("HeapAlloc before: %d bytes\n", before)
fmt.Printf("HeapAlloc after: %d bytes\n", after)
fmt.Printf("Difference: %d bytes\n", after-before)
}
Результат выполнения кода:
"HeapAlloc before: 123456 bytes"
"HeapAlloc after: 8234567 bytes"
"Difference: 8111111 bytes"
Пример отслеживания сборки мусора
Проанализируем время и частоту сборок мусора:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
// Trigger GC manually
runtime.GC()
time.Sleep(100 * time.Millisecond)
runtime.ReadMemStats(&stats)
fmt.Printf("Number of GC cycles: %d\n", stats.NumGC)
fmt.Printf("Total GC pause time: %d ns\n", stats.PauseTotalNs)
fmt.Printf("Last GC time: %d ns\n", stats.LastGC)
fmt.Printf("Next GC target: %d bytes\n", stats.NextGC)
}
Результат выполнения кода:
"Number of GC cycles: 43"
"Total GC pause time: 12345678 ns"
"Last GC time: 1234567890123456 ns"
"Next GC target: 16777216 bytes"
Смотрите также
-
функцию
runtime.ReadMemStats,
которая заполняет структуруMemStatsактуальными данными -
функцию
runtime.GC,
которая запускает сборку мусора вручную -
функцию
runtime.NumGoroutine,
которая возвращает количество активных горутин -
функцию
runtime.GOMAXPROCS,
которая управляет количеством используемых процессоров