Last active
August 5, 2022 16:25
-
-
Save kaishuu0123/84c32271f21f9878e79a199f1d68acf2 to your computer and use it in GitHub Desktop.
Golang Memory Usage (like vmstat)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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