In this post we show how you can print memory usage in golang. We do this by outputting the current state of memory at any given time to show how much ram has been allocated and gc cycles made. We have created a function PrintMemUsage() to help out, so you can call this when ever you need to know.
All the info we need can be acquired through the runtime [docs] package, which allows us to read the state of the memory into the MemStats struct. It returns stats like how much memory the program is using, how much of it the OS has allocated to it and the number of garbage collections.
packagemainimport("runtime""fmt""time")funcmain(){vardata[][]intfori:=0;i<4;i++{// Example data:
// Allocate memory using make() and append to data var (so it doesn't get
// garbage collected). This is to create an ever increasing memory usage
// which we can track. We're just using []int as an example.
a:=make([]int,0,999999)data=append(data,a)// Print our memory usage at each interval
PrintMemUsage()time.Sleep(time.Second)}// Clear our memory and print usage, unless the GC has run 'Alloc' will remain the same
data=nilPrintMemUsage()// Force GC to clear up, should see a memory drop
runtime.GC()PrintMemUsage()}// PrintMemUsage outputs the current, total and OS memory being used. As well as the
// number of garage collection cycles completed. For info on each,
// see: https://golang.org/pkg/runtime/#MemStats
funcPrintMemUsage(){varmruntime.MemStatsruntime.ReadMemStats(&m)fmt.Printf("Alloc = %v MiB",m.Alloc/1024/1024)fmt.Printf("\tTotalAlloc = %v MiB",m.TotalAlloc/1024/1024)fmt.Printf("\tSys = %v MiB",m.Sys/1024/1024)fmt.Printf("\tNumGC = %v\n",m.NumGC)}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.