Skip to content

Instantly share code, notes, and snippets.

@kaishuu0123
Last active August 5, 2022 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaishuu0123/84c32271f21f9878e79a199f1d68acf2 to your computer and use it in GitHub Desktop.
Save kaishuu0123/84c32271f21f9878e79a199f1d68acf2 to your computer and use it in GitHub Desktop.
Golang Memory Usage (like vmstat)
import (
"fmt"
"time
)
func main() {
fmt.Println("Hello, world")
go func() {
t := time.NewTicker(3 * time.Second) // 3秒おき
for {
select {
case <-t.C:
PrintMemUsage()
}
}
t.Stop() // タイマ停止
}()
for {
// loop
}
// 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.
func PrintMemUsage() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
fmt.Printf("\tNumGC = %v\n", m.NumGC)
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment