tags | |||
---|---|---|---|
|
Measure memory statistics at runtime
import (
"runtime"
)
func main() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
}
You can use the runtime
package to read memory statistics of your
go applications
The package provides the MemStats
structs that can be populated
with all the memory statistics
The .Alloc
attritbute represents the number of bytes currently
allocated for heap objects in a go program
- This means it's the memroy currently in used by our program
- You coudl use this stats to for example:
- Locate a memory leak
- Find out a large allocation, in the case that there is a suddenly spike in the allocated bytes
The .TotalAlloc
attribute describes the acumulate total number of bytes
allocated for heap objects since the program started running
- This means this value only ever increases
- We can use this to see how memory intensive is our program throughout it's lifetime
The .Sys
attribute represents the total number of bytes of memory obtained
from the operating system
- This inlcudes all
heap
and nonheap
memory used- Like it includes memory reserved but not necessarily used
- This basically represents all the memory that the
runtime
has obtained from the operating system - This can be seen as the total foot print of our program in the system's memory
The .NumGC
attribute represents the number of completed garbage collection
cycles since the program started
- This field is increased whenever the
go
runtime cleans up memory that is no longer being used - Frecuent garbage collections might indicate high memory preasure
- Also
GC
is a stop the world action that can slow down your program's operations
- Also
You can use the ReadMemStats
function to read all the memory statistics
of your programm at a given point in time and write them to the MemStats
struct for inspecting them
The attributes of the
MemStats
struct are alluint64
types that represent sizes inbytes
if you want to get another representation likemegabytes
then you will need to do that conversion your self
import (
"runtime"
)
func printMemStats() {
var stats runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Alloc = %v MB\n", bytesToMegabytes(stats.Alloc))
}
func bytesToMegabytes(bytes uint64) uint64 {
kilobytes := bytes / 1000
megabytes := kilobytes / 1000
return megabytes
}
func main() {
fmt.Println("Mem stats before:")
printMemStats()
mySlice := make([]int, 1_000_000)
for index, value := range mySlice {
mySlice[index] = value
}
fmt.Println("Mem stats after:")
printMemStats()
}