runtime.go 682 B

12345678910111213141516171819202122232425262728293031
  1. package prof
  2. import (
  3. "fmt"
  4. "runtime"
  5. "time"
  6. )
  7. const (
  8. defaultInterval = time.Second * 5
  9. mega = 1024 * 1024
  10. )
  11. // DisplayStats prints the goroutine, memory, GC stats with given interval, default to 5 seconds.
  12. func DisplayStats(interval ...time.Duration) {
  13. duration := defaultInterval
  14. for _, val := range interval {
  15. duration = val
  16. }
  17. go func() {
  18. ticker := time.NewTicker(duration)
  19. defer ticker.Stop()
  20. for range ticker.C {
  21. var m runtime.MemStats
  22. runtime.ReadMemStats(&m)
  23. fmt.Printf("Goroutines: %d, Alloc: %vm, TotalAlloc: %vm, Sys: %vm, NumGC: %v\n",
  24. runtime.NumGoroutine(), m.Alloc/mega, m.TotalAlloc/mega, m.Sys/mega, m.NumGC)
  25. }
  26. }()
  27. }