1
0

runtime.go 829 B

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