Periodically count goroutines and print memory usage. Cheap and useful to find memory leaks and goroutine leaks.
```go
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}
// 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 StartBackgroundGoroutinePrinter() {
go func() {
for {
time.Sleep(time.Second * 5)
runtime.GC()
fmt.Println()
printMemUsage()
fmt.Printf("======= Goroutines: %d\n\n", runtime.NumGoroutine())
}
}()
}
```